import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useCreateBrief } from '../../hooks/useJob';
import { useToastContext } from '../../contexts/ToastContext';
import { useAllProjects, useBriefAssignees } from '../../hooks/useClients';

const ALL_LANGUAGES: { code: string; label: string }[] = [
  { code: 'en', label: 'EN' },
  { code: 'en-US', label: 'EN-US' },
  { code: 'en-GB', label: 'EN-GB' },
  { code: 'en-CA', label: 'EN-CA' },
  { code: 'fr', label: 'FR' },
  { code: 'fr-FR', label: 'FR-FR' },
  { code: 'fr-CA', label: 'FR-CA' },
  { code: 'de', label: 'DE' },
  { code: 'de-DE', label: 'DE-DE' },
  { code: 'es', label: 'ES' },
  { code: 'es-ES', label: 'ES-ES' },
  { code: 'es-419', label: 'ES-LATAM' },
  { code: 'es-MX', label: 'ES-MX' },
  { code: 'it', label: 'IT' },
  { code: 'it-IT', label: 'IT-IT' },
  { code: 'pt', label: 'PT' },
  { code: 'pt-BR', label: 'PT-BR' },
  { code: 'pt-PT', label: 'PT-PT' },
  { code: 'nl', label: 'NL' },
  { code: 'nl-NL', label: 'NL-NL' },
  { code: 'pl', label: 'PL' },
  { code: 'pl-PL', label: 'PL-PL' },
  { code: 'sv', label: 'SV' },
  { code: 'da', label: 'DA' },
  { code: 'nb', label: 'NB' },
  { code: 'fi', label: 'FI' },
  { code: 'cs', label: 'CS' },
  { code: 'cs-CZ', label: 'CS-CZ' },
  { code: 'sk', label: 'SK' },
  { code: 'hu', label: 'HU' },
  { code: 'ro', label: 'RO' },
  { code: 'uk', label: 'UK' },
  { code: 'ru', label: 'RU' },
  { code: 'tr', label: 'TR' },
  { code: 'tr-TR', label: 'TR-TR' },
  { code: 'id', label: 'ID' },
  { code: 'id-ID', label: 'ID-ID' },
  { code: 'vi', label: 'VI' },
  { code: 'th', label: 'TH' },
  { code: 'ja', label: 'JA' },
  { code: 'ja-JP', label: 'JA-JP' },
  { code: 'ko', label: 'KO' },
  { code: 'ko-KR', label: 'KO-KR' },
  { code: 'zh', label: 'ZH' },
  { code: 'ar', label: 'AR' },
  { code: 'hi', label: 'HI' },
  { code: 'bn', label: 'BN' },
  { code: 'mr', label: 'MR' },
  { code: 'ta', label: 'TA' },
  { code: 'te', label: 'TE' },
];

export function NewBrief() {
  const navigate = useNavigate();
  const toast = useToastContext();
  const createBriefMutation = useCreateBrief();

  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [languages, setLanguages] = useState<string[]>([]);
  const [deadline, setDeadline] = useState('');
  const [projectId, setProjectId] = useState('');
  const [assigneeId, setAssigneeId] = useState('');

  // Requested outputs
  const [captionsVtt, setCaptionsVtt] = useState(true);
  const [adVtt, setAdVtt] = useState(true);
  const [adMp3, setAdMp3] = useState(true);
  const [accessibleMp4, setAccessibleMp4] = useState(false);
  const [accessibleMethod, setAccessibleMethod] = useState<'overlay' | 'pause_insert'>('pause_insert');
  const [sdhVtt, setSdhVtt] = useState(false);
  const [descriptiveTranscript, setDescriptiveTranscript] = useState(false);
  const [sourceHasAd, setSourceHasAd] = useState(false);

  const { data: projects = [] } = useAllProjects();
  const { data: assignees = [] } = useBriefAssignees();

  const toggleLang = (lang: string) => {
    setLanguages(prev =>
      prev.includes(lang) ? prev.filter(l => l !== lang) : [...prev, lang]
    );
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim()) {
      toast.toastOnly.error('Title is required');
      return;
    }
    try {
      const brief = await createBriefMutation.mutateAsync({
        title: title.trim(),
        description: description.trim() || undefined,
        requested_outputs: {
          captions_vtt: captionsVtt,
          audio_description_vtt: adVtt,
          audio_description_mp3: adMp3,
          accessible_video_mp4: accessibleMp4,
          accessible_video_method: accessibleMp4 ? accessibleMethod : undefined,
          sdh_vtt: sdhVtt,
          descriptive_transcript: descriptiveTranscript,
          languages,
          transcreation: [],
          translation_mode: 'traditional',
        },
        languages,
        deadline: deadline || undefined,
        project_id: projectId || undefined,
        assignee_id: assigneeId || undefined,
        source_has_ad: sourceHasAd,
      });
      toast.toastOnly.success('Brief created');
      navigate(`/briefs/${brief.id}`);
    } catch {
      toast.toastOnly.error('Failed to create brief');
    }
  };

  return (
    <div className="container mx-auto px-4 py-8 max-w-2xl">
      <div className="flex items-center gap-3 mb-6">
        <Link to="/briefs" className="text-gray-500 hover:text-gray-700 text-sm">← Briefs</Link>
        <h1 className="text-2xl font-bold text-gray-900">New Job Brief</h1>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6 bg-white border border-gray-200 rounded-lg p-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Title *</label>
          <input
            type="text"
            value={title}
            onChange={e => setTitle(e.target.value)}
            className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500"
            placeholder="e.g. Product launch video — EN/FR/DE"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            rows={3}
            className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500"
            placeholder="Optional context for the production team"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Project</label>
          <select
            value={projectId}
            onChange={e => setProjectId(e.target.value)}
            className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
          >
            <option value="">— None —</option>
            {projects.map(p => (
              <option key={p.id} value={p.id}>{p.name}</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Assign To</label>
          <select
            value={assigneeId}
            onChange={e => setAssigneeId(e.target.value)}
            className="w-full border border-gray-300 rounded px-3 py-2 text-sm"
          >
            <option value="">— Unassigned —</option>
            {assignees.map(u => (
              <option key={u.id} value={u.id}>
                {u.full_name || u.email} ({u.role.replace('_', ' ')})
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Requested Outputs</label>
          <div className="space-y-3">
            {([
              [captionsVtt, setCaptionsVtt, 'Captions (VTT)', 'Closed captions in WebVTT format'],
              [adVtt, setAdVtt, 'Audio Descriptions (VTT)', 'Audio description cues in WebVTT format'],
              [adMp3, setAdMp3, 'Audio Descriptions (MP3)', 'Synthesised audio description track'],
              [sdhVtt, setSdhVtt, 'SDH Captions (VTT)', 'Subtitles for Deaf and Hard of Hearing — includes speaker labels and sound effects'],
              [descriptiveTranscript, setDescriptiveTranscript, 'Descriptive Transcript', 'Full text transcript with integrated audio descriptions'],
            ] as [boolean, (v: boolean) => void, string, string][]).map(([val, setter, label, hint]) => (
              <label key={label} className="flex items-start gap-2 text-sm text-gray-700 cursor-pointer">
                <input
                  type="checkbox"
                  checked={val}
                  onChange={e => setter(e.target.checked)}
                  className="rounded mt-0.5 flex-shrink-0"
                />
                <span>
                  <span className="font-medium">{label}</span>
                  <span className="text-gray-400 ml-1">— {hint}</span>
                </span>
              </label>
            ))}

            {/* Accessible Video — with method selector */}
            <div className="space-y-2">
              <label className="flex items-start gap-2 text-sm text-gray-700 cursor-pointer">
                <input
                  type="checkbox"
                  checked={accessibleMp4}
                  onChange={e => setAccessibleMp4(e.target.checked)}
                  className="rounded mt-0.5 flex-shrink-0"
                />
                <span>
                  <span className="font-medium">Accessible Video (MP4)</span>
                  <span className="text-gray-400 ml-1">— Video with embedded audio descriptions</span>
                </span>
              </label>
              {accessibleMp4 && (
                <div className="ml-6 flex gap-4">
                  {(['pause_insert', 'overlay'] as const).map(method => (
                    <label key={method} className="flex items-center gap-1.5 text-sm cursor-pointer">
                      <input
                        type="radio"
                        name="accessible_method"
                        value={method}
                        checked={accessibleMethod === method}
                        onChange={() => setAccessibleMethod(method)}
                        className="text-indigo-600"
                      />
                      <span>{method === 'pause_insert' ? 'Pause Insert' : 'Voice Overlay'}</span>
                    </label>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Source Video</label>
          <label className="flex items-start gap-2 text-sm text-gray-700 cursor-pointer">
            <input
              type="checkbox"
              checked={sourceHasAd}
              onChange={e => setSourceHasAd(e.target.checked)}
              className="rounded mt-0.5 flex-shrink-0"
            />
            <span>
              <span className="font-medium">Source video already contains audio descriptions</span>
              <span className="text-gray-400 ml-1">— AI will not generate new AD for this job</span>
            </span>
          </label>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Languages
            {languages.length > 0 && (
              <span className="ml-2 text-xs text-indigo-600 font-normal">{languages.length} selected</span>
            )}
          </label>
          <div className="flex flex-wrap gap-2 max-h-40 overflow-y-auto p-2 border border-gray-200 rounded">
            {ALL_LANGUAGES.map(({ code, label }) => (
              <button
                type="button"
                key={code}
                onClick={() => toggleLang(code)}
                className={`px-2 py-1 text-xs rounded border transition-colors ${
                  languages.includes(code)
                    ? 'bg-indigo-600 text-white border-indigo-600'
                    : 'bg-white text-gray-600 border-gray-300 hover:border-indigo-400'
                }`}
              >
                {label}
              </button>
            ))}
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Deadline</label>
          <input
            type="date"
            value={deadline}
            onChange={e => setDeadline(e.target.value)}
            className="border border-gray-300 rounded px-3 py-2 text-sm"
          />
        </div>

        <div className="flex gap-3">
          <button
            type="submit"
            disabled={createBriefMutation.isPending}
            className="px-6 py-2 bg-indigo-600 text-white text-sm rounded hover:bg-indigo-700 disabled:opacity-50"
          >
            {createBriefMutation.isPending ? 'Creating...' : 'Create Brief'}
          </button>
          <Link to="/briefs" className="px-6 py-2 text-sm text-gray-600 hover:text-gray-800">
            Cancel
          </Link>
        </div>
      </form>
    </div>
  );
}
