'use client';

import { useState } from 'react';
import { Plus, Trash2, X } from 'lucide-react';
import type { Orchestration, OrchestrationStep } from '../../lib/types';

interface OrchestrationEditorProps {
  orchestration?: Orchestration;
  models: string[];
  onSave: (orch: Orchestration) => void;
  onClose: () => void;
}

export function OrchestrationEditor({
  orchestration,
  models,
  onSave,
  onClose,
}: OrchestrationEditorProps) {
  const [name, setName] = useState(orchestration?.name || '');
  const [mode, setMode] = useState<Orchestration['mode']>(orchestration?.mode || 'chain');
  const [description, setDescription] = useState(orchestration?.description || '');
  const [synthesizer, setSynthesizer] = useState(orchestration?.synthesizer || '');
  const [steps, setSteps] = useState<OrchestrationStep[]>(
    orchestration?.steps || [{ model: models[0] || '' }]
  );

  const addStep = () => {
    setSteps(prev => [...prev, { model: models[0] || '' }]);
  };

  const removeStep = (idx: number) => {
    setSteps(prev => prev.filter((_, i) => i !== idx));
  };

  const updateStep = (idx: number, partial: Partial<OrchestrationStep>) => {
    setSteps(prev => prev.map((s, i) => (i === idx ? { ...s, ...partial } : s)));
  };

  const handleSave = () => {
    if (!name.trim() || steps.length === 0) return;
    onSave({
      id: orchestration?.id || crypto.randomUUID(),
      name: name.trim(),
      mode,
      steps,
      synthesizer: mode === 'vote' ? synthesizer : undefined,
      description: description.trim() || undefined,
    });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
      <div className="w-full max-w-lg rounded-lg border border-white/10 bg-[var(--bg-elevated)] p-5">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-[var(--text-primary)]">
            {orchestration ? 'Edit Orchestration' : 'New Orchestration'}
          </h2>
          <button
            type="button"
            onClick={onClose}
            className="text-[var(--text-tertiary)] hover:text-[var(--text-primary)]"
          >
            <X size={18} />
          </button>
        </div>

        <div className="space-y-3">
          <div>
            <label className="mb-1 block text-xs text-[var(--text-secondary)]">Name *</label>
            <input
              value={name}
              onChange={e => setName(e.target.value)}
              className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              placeholder="My orchestration"
            />
          </div>

          <div>
            <label className="mb-1 block text-xs text-[var(--text-secondary)]">Description</label>
            <input
              value={description}
              onChange={e => setDescription(e.target.value)}
              className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              placeholder="What does this orchestration do?"
            />
          </div>

          <div>
            <label className="mb-1 block text-xs text-[var(--text-secondary)]">Mode</label>
            <div className="flex gap-2">
              {(['chain', 'race', 'vote'] as const).map(m => (
                <button
                  key={m}
                  type="button"
                  onClick={() => setMode(m)}
                  className={`rounded border px-3 py-1 text-xs capitalize ${mode === m ? 'border-[var(--accent-primary)] bg-[var(--accent-primary)]/20 text-[var(--accent-primary)]' : 'border-white/10 text-[var(--text-secondary)] hover:text-[var(--text-primary)]'}`}
                >
                  {m}
                </button>
              ))}
            </div>
            <p className="mt-1 text-[10px] text-[var(--text-tertiary)]">
              {mode === 'chain' && 'Sequential: each step output feeds into the next via {prev}'}
              {mode === 'race' && 'Parallel: same prompt to all models, pick the best'}
              {mode === 'vote' &&
                'Consensus: all models respond, synthesizer produces final answer'}
            </p>
          </div>

          <div>
            <div className="mb-1 flex items-center justify-between">
              <label className="text-xs text-[var(--text-secondary)]">Steps ({steps.length})</label>
              <button
                type="button"
                onClick={addStep}
                className="inline-flex items-center gap-1 text-[10px] text-[var(--accent-primary)] hover:underline"
              >
                <Plus size={10} /> Add step
              </button>
            </div>
            <div className="space-y-2">
              {steps.map((step, idx) => (
                <div
                  key={idx}
                  className="flex items-start gap-2 rounded border border-white/10 bg-[var(--surface-card)] p-2"
                >
                  <span className="mt-1 text-[10px] text-[var(--text-tertiary)]">#{idx + 1}</span>
                  <div className="min-w-0 flex-1 space-y-1">
                    <select
                      value={step.model}
                      onChange={e => updateStep(idx, { model: e.target.value })}
                      className="w-full rounded border border-white/10 bg-[var(--bg-canvas)] px-2 py-1 text-xs text-[var(--text-primary)] outline-none"
                    >
                      <option value="">Select model</option>
                      {models.map(m => (
                        <option key={m} value={m}>
                          {m}
                        </option>
                      ))}
                    </select>
                    {mode === 'chain' && (
                      <input
                        value={step.systemPrompt || ''}
                        onChange={e => updateStep(idx, { systemPrompt: e.target.value })}
                        placeholder="System prompt (optional, use {prev} for previous output)"
                        className="w-full rounded border border-white/10 bg-[var(--bg-canvas)] px-2 py-1 text-[11px] text-[var(--text-secondary)] outline-none"
                      />
                    )}
                  </div>
                  {steps.length > 1 && (
                    <button
                      type="button"
                      onClick={() => removeStep(idx)}
                      className="mt-1 text-[var(--text-tertiary)] hover:text-[var(--danger)]"
                    >
                      <Trash2 size={12} />
                    </button>
                  )}
                </div>
              ))}
            </div>
          </div>

          {mode === 'vote' && (
            <div>
              <label className="mb-1 block text-xs text-[var(--text-secondary)]">
                Synthesizer Model
              </label>
              <select
                value={synthesizer}
                onChange={e => setSynthesizer(e.target.value)}
                className="w-full rounded border border-white/10 bg-[var(--surface-card)] px-3 py-1.5 text-sm text-[var(--text-primary)] outline-none"
              >
                <option value="">Select synthesizer</option>
                {models.map(m => (
                  <option key={m} value={m}>
                    {m}
                  </option>
                ))}
              </select>
            </div>
          )}
        </div>

        <div className="mt-5 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="rounded border border-white/10 px-4 py-1.5 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleSave}
            disabled={!name.trim() || steps.length === 0}
            className="rounded bg-[var(--accent-primary)] px-4 py-1.5 text-sm text-white disabled:opacity-50"
          >
            Save
          </button>
        </div>
      </div>
    </div>
  );
}
