'use client';

import { useEffect, useMemo, useState } from 'react';
import type { QuickAction } from '../../lib/types';

interface QuickActionEditorProps {
  open: boolean;
  editing?: QuickAction | null;
  onClose: () => void;
  onSave: (action: QuickAction) => Promise<void>;
}

const CATEGORIES: QuickAction['category'][] = [
  'code',
  'writing',
  'analysis',
  'creative',
  'devops',
  'custom',
];

const MODEL_HINTS = ['fast', 'coding', 'reasoning', 'chat', 'vision'];

export function QuickActionEditor({ open, editing, onClose, onSave }: QuickActionEditorProps) {
  const [name, setName] = useState('');
  const [icon, setIcon] = useState('✨');
  const [category, setCategory] = useState<QuickAction['category']>('custom');
  const [description, setDescription] = useState('');
  const [modelHint, setModelHint] = useState('chat');
  const [systemPrompt, setSystemPrompt] = useState('');
  const [userTemplate, setUserTemplate] = useState('');
  const [hotkey, setHotkey] = useState('');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    if (editing) {
      setName(editing.name);
      setIcon(editing.icon);
      setCategory(editing.category);
      setDescription(editing.description);
      setModelHint(editing.modelHint);
      setSystemPrompt(editing.systemPrompt);
      setUserTemplate(editing.userTemplate);
      setHotkey(editing.hotkey || '');
      return;
    }

    setName('');
    setIcon('✨');
    setCategory('custom');
    setDescription('');
    setModelHint('chat');
    setSystemPrompt('');
    setUserTemplate('');
    setHotkey('');
  }, [open, editing]);

  const canSave = useMemo(() => {
    return name.trim().length > 0 && systemPrompt.trim().length > 0;
  }, [name, systemPrompt]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-2xl rounded-lg border border-white/10 bg-[var(--surface-card)] p-4"
        onClick={e => e.stopPropagation()}
      >
        <h2 className="mb-3 text-lg font-semibold text-[var(--text-primary)]">
          {editing ? 'Edit Quick Action' : 'Create Quick Action'}
        </h2>

        <div className="grid gap-3 md:grid-cols-2">
          <label className="text-sm text-[var(--text-secondary)]">
            Name
            <input
              value={name}
              onChange={e => setName(e.target.value)}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            />
          </label>

          <label className="text-sm text-[var(--text-secondary)]">
            Icon
            <input
              value={icon}
              onChange={e => setIcon(e.target.value)}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            />
          </label>

          <label className="text-sm text-[var(--text-secondary)]">
            Category
            <select
              value={category}
              onChange={e => setCategory(e.target.value as QuickAction['category'])}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            >
              {CATEGORIES.map(item => (
                <option key={item} value={item}>
                  {item}
                </option>
              ))}
            </select>
          </label>

          <label className="text-sm text-[var(--text-secondary)]">
            Model Hint
            <select
              value={modelHint}
              onChange={e => setModelHint(e.target.value)}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            >
              {MODEL_HINTS.map(item => (
                <option key={item} value={item}>
                  {item}
                </option>
              ))}
            </select>
          </label>

          <label className="md:col-span-2 text-sm text-[var(--text-secondary)]">
            Description
            <input
              value={description}
              onChange={e => setDescription(e.target.value)}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            />
          </label>

          <label className="md:col-span-2 text-sm text-[var(--text-secondary)]">
            System Prompt
            <textarea
              rows={5}
              value={systemPrompt}
              onChange={e => setSystemPrompt(e.target.value)}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            />
          </label>

          <label className="md:col-span-2 text-sm text-[var(--text-secondary)]">
            User Template
            <textarea
              rows={4}
              value={userTemplate}
              onChange={e => setUserTemplate(e.target.value)}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            />
          </label>

          <label className="text-sm text-[var(--text-secondary)]">
            Hotkey (optional)
            <input
              value={hotkey}
              onChange={e => setHotkey(e.target.value)}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            />
          </label>
        </div>

        <div className="mt-4 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="rounded border border-white/10 px-3 py-1 text-sm text-[var(--text-secondary)] hover:bg-white/5"
          >
            Cancel
          </button>
          <button
            type="button"
            disabled={!canSave || saving}
            onClick={async () => {
              setSaving(true);
              const action: QuickAction = {
                id: editing?.id || crypto.randomUUID(),
                name: name.trim(),
                icon: icon.trim() || '✨',
                category,
                description: description.trim(),
                modelHint,
                systemPrompt: systemPrompt.trim(),
                userTemplate: userTemplate.trim(),
                builtin: false,
                hotkey: hotkey.trim() || undefined,
                usageCount: editing?.usageCount ?? 0,
                lastUsed: editing?.lastUsed,
              };
              await onSave(action);
              setSaving(false);
              onClose();
            }}
            className="rounded bg-[var(--accent-primary)] px-3 py-1 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
          >
            {saving ? 'Saving...' : 'Save'}
          </button>
        </div>
      </div>
    </div>
  );
}
