'use client';

import { useEffect, useState } from 'react';
import type { Agent, AgentTool } from '../../lib/types';

interface AgentEditorProps {
  open: boolean;
  editing?: Agent | null;
  onClose: () => void;
  onSave: (agent: Agent) => Promise<void>;
}

const TOOL_OPTIONS: AgentTool[] = ['file_read', 'vision', 'voice_input'];

export function AgentEditor({ open, editing, onClose, onSave }: AgentEditorProps) {
  const [name, setName] = useState('');
  const [icon, setIcon] = useState('🤖');
  const [description, setDescription] = useState('');
  const [model, setModel] = useState('chat');
  const [temperature, setTemperature] = useState<number>(0.7);
  const [systemPrompt, setSystemPrompt] = useState('');
  const [welcomeMessage, setWelcomeMessage] = useState('');
  const [examplePrompts, setExamplePrompts] = useState('');
  const [responseFormat, setResponseFormat] = useState<Agent['responseFormat']>('markdown');
  const [tools, setTools] = useState<AgentTool[]>(['file_read']);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    if (editing) {
      setName(editing.name);
      setIcon(editing.icon);
      setDescription(editing.description);
      setModel(editing.model);
      setTemperature(editing.temperature ?? 0.7);
      setSystemPrompt(editing.systemPrompt);
      setWelcomeMessage(editing.welcomeMessage || '');
      setExamplePrompts((editing.examplePrompts || []).join('\n'));
      setResponseFormat(editing.responseFormat || 'markdown');
      setTools(editing.tools || ['file_read']);
      return;
    }

    setName('');
    setIcon('🤖');
    setDescription('');
    setModel('chat');
    setTemperature(0.7);
    setSystemPrompt('');
    setWelcomeMessage('');
    setExamplePrompts('');
    setResponseFormat('markdown');
    setTools(['file_read']);
  }, [open, editing]);

  if (!open) return null;

  const canSave = name.trim().length > 0 && systemPrompt.trim().length > 0;

  return (
    <div
      className="fixed inset-0 z-[70] flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-3xl 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 Agent' : 'Create Agent'}
        </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)] md:col-span-2">
            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="text-sm text-[var(--text-secondary)]">
            Model
            <input
              value={model}
              onChange={e => setModel(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)]">
            Temperature ({temperature.toFixed(1)})
            <input
              type="range"
              min={0}
              max={2}
              step={0.1}
              value={temperature}
              onChange={e => setTemperature(Number(e.target.value))}
              className="mt-2 w-full"
            />
          </label>

          <label className="text-sm text-[var(--text-secondary)] md:col-span-2">
            System Prompt
            <textarea
              rows={6}
              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="text-sm text-[var(--text-secondary)] md:col-span-2">
            Welcome Message
            <input
              value={welcomeMessage}
              onChange={e => setWelcomeMessage(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)] md:col-span-2">
            Example Prompts (one per line)
            <textarea
              rows={4}
              value={examplePrompts}
              onChange={e => setExamplePrompts(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)]">
            Response Format
            <select
              value={responseFormat}
              onChange={e => setResponseFormat(e.target.value as Agent['responseFormat'])}
              className="mt-1 w-full rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-[var(--text-primary)] outline-none"
            >
              <option value="markdown">markdown</option>
              <option value="json">json</option>
              <option value="code">code</option>
              <option value="plain">plain</option>
            </select>
          </label>

          <div className="text-sm text-[var(--text-secondary)]">
            Tools
            <div className="mt-2 space-y-1">
              {TOOL_OPTIONS.map(tool => (
                <label key={tool} className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={tools.includes(tool)}
                    onChange={e => {
                      setTools(prev => {
                        if (e.target.checked) return Array.from(new Set([...prev, tool]));
                        return prev.filter(item => item !== tool);
                      });
                    }}
                  />
                  <span>{tool}</span>
                </label>
              ))}
            </div>
          </div>
        </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 agent: Agent = {
                id: editing?.id || crypto.randomUUID(),
                name: name.trim(),
                icon: icon.trim() || '🤖',
                description: description.trim(),
                model: model.trim() || 'chat',
                systemPrompt: systemPrompt.trim(),
                temperature,
                tools,
                welcomeMessage: welcomeMessage.trim() || undefined,
                examplePrompts: examplePrompts
                  .split('\n')
                  .map(s => s.trim())
                  .filter(Boolean),
                constraints: editing?.constraints,
                responseFormat,
                builtin: false,
                conversationCount: editing?.conversationCount ?? 0,
                createdAt: editing?.createdAt ?? Date.now(),
              };
              await onSave(agent);
              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 Agent'}
          </button>
        </div>
      </div>
    </div>
  );
}
