import { useState, useRef } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '../../../lib/api';
import { useToastContext } from '../../../contexts/ToastContext';

const KNOWN_LOCALES: { code: string; label: string }[] = [
  { code: 'en-GB', label: 'English (UK)' },
  { code: 'en-US', label: 'English (US)' },
  { code: 'en-CA', label: 'English (Canada)' },
  { code: 'de-DE', label: 'German' },
  { code: 'fr-FR', label: 'French (France)' },
  { code: 'fr-CA', label: 'French (Canada)' },
  { code: 'es-ES', label: 'Spanish (Spain)' },
  { code: 'es-MX', label: 'Spanish (Mexico)' },
  { code: 'es-419', label: 'Spanish (Latin America)' },
  { code: 'it-IT', label: 'Italian' },
  { code: 'pt-BR', label: 'Portuguese (Brazil)' },
  { code: 'pt-PT', label: 'Portuguese (Portugal)' },
  { code: 'nl-NL', label: 'Dutch' },
  { code: 'pl-PL', label: 'Polish' },
  { code: 'cs-CZ', label: 'Czech' },
  { code: 'tr-TR', label: 'Turkish' },
  { code: 'ko-KR', label: 'Korean' },
  { code: 'ja-JP', label: 'Japanese' },
  { code: 'id-ID', label: 'Indonesian' },
];

export function GlossaryUpload() {
  const { clientId } = useParams<{ clientId: string }>();
  const navigate = useNavigate();
  const toast = useToastContext();
  const qc = useQueryClient();

  const [file, setFile] = useState<File | null>(null);
  const [name, setName] = useState('');
  const [sourceLocale, setSourceLocale] = useState('en-GB');
  const [sourceLocaleCol, setSourceLocaleCol] = useState('');
  const [description, setDescription] = useState('');
  const [changeNote, setChangeNote] = useState('');
  const [dragOver, setDragOver] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const uploadMut = useMutation({
    mutationFn: () => apiClient.uploadGlossary(
      clientId!,
      file!,
      name.trim(),
      sourceLocale,
      sourceLocaleCol.trim(),
      description.trim() || undefined,
      changeNote.trim() || undefined,
    ),
    onSuccess: (g) => {
      qc.invalidateQueries({ queryKey: ['glossaries', clientId] });
      toast.success(`Glossary "${g.name}" uploaded — embedding in background`);
      navigate(`/admin/clients/${clientId}/glossaries/${g.id}`);
    },
    onError: (err: unknown) => {
      const msg = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ?? 'Upload failed';
      toast.error(msg);
    },
  });

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);
    const f = e.dataTransfer.files[0];
    if (f && f.name.endsWith('.xlsx')) setFile(f);
    else toast.error('Only .xlsx files are accepted');
  };

  const canSubmit = !!file && !!name.trim() && !!sourceLocale && !!sourceLocaleCol.trim() && !uploadMut.isPending;

  return (
    <div className="container mx-auto px-4 py-8 max-w-xl space-y-6">
      <div>
        <p className="text-sm text-gray-400 mb-1">
          ← <Link to={`/admin/clients/${clientId}/glossaries`} className="hover:text-blue-600">Glossaries</Link>
        </p>
        <h1 className="text-2xl font-bold text-gray-900">Upload glossary</h1>
        <p className="text-sm text-gray-500 mt-1">Upload an xlsx file with terminology translations.</p>
      </div>

      {/* Drop zone */}
      <div
        className={`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-colors ${
          dragOver ? 'border-blue-400 bg-blue-50' : 'border-gray-300 hover:border-gray-400'
        }`}
        onClick={() => fileInputRef.current?.click()}
        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={handleDrop}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          className="hidden"
          onChange={(e) => {
            const f = e.target.files?.[0];
            if (f) setFile(f);
          }}
        />
        {file ? (
          <div>
            <p className="text-sm font-medium text-gray-900">{file.name}</p>
            <p className="text-xs text-gray-400 mt-1">{(file.size / 1024 / 1024).toFixed(1)} MB</p>
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); setFile(null); }}
              className="mt-2 text-xs text-red-500 hover:text-red-700"
            >
              Remove
            </button>
          </div>
        ) : (
          <div className="text-gray-400">
            <p className="text-sm font-medium">Drop .xlsx file here or click to browse</p>
            <p className="text-xs mt-1">Max 50 MB</p>
          </div>
        )}
      </div>

      {/* Form fields */}
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Glossary name *</label>
          <input
            type="text"
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="e.g. 3M Master Terminology"
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Source language *</label>
          <select
            value={sourceLocale}
            onChange={e => setSourceLocale(e.target.value)}
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            {KNOWN_LOCALES.map(l => (
              <option key={l.code} value={l.code}>{l.label} ({l.code})</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Source column header in xlsx *</label>
          <input
            type="text"
            value={sourceLocaleCol}
            onChange={e => setSourceLocaleCol(e.target.value)}
            placeholder="e.g. en_gb  or  English (GB)"
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <p className="text-xs text-gray-400 mt-1">Must exactly match the column header in the xlsx file (case-insensitive).</p>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Description (optional)</label>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            rows={2}
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Change note (optional)</label>
          <input
            type="text"
            value={changeNote}
            onChange={e => setChangeNote(e.target.value)}
            placeholder="e.g. Initial import Q1 2026"
            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
      </div>

      <div className="flex gap-3 pt-2">
        <button
          type="button"
          onClick={() => navigate(`/admin/clients/${clientId}/glossaries`)}
          className="px-4 py-2 border border-gray-300 text-sm rounded-lg hover:bg-gray-50"
        >
          Cancel
        </button>
        <button
          type="button"
          disabled={!canSubmit}
          onClick={() => uploadMut.mutate()}
          className="flex-1 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50"
        >
          {uploadMut.isPending ? 'Uploading…' : 'Upload glossary'}
        </button>
      </div>
    </div>
  );
}
