import { useState, useRef } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '../../../lib/api';
import { useToastContext } from '../../../contexts/ToastContext';
import { useAuthStore } from '../../../lib/auth';
import type { GlossaryVersion, GlossaryDetail as GlossaryDetailType } from '../../../types/api';

type Tab = 'terms' | 'versions';

function EmbeddingPill({ v }: { v: GlossaryVersion }) {
  const pct = v.term_count > 0 ? Math.round((v.embedded_count / v.term_count) * 100) : 0;
  switch (v.embedding_status) {
    case 'done': return <span className="text-xs text-green-600 font-medium">Embedded ({v.embedded_count}/{v.term_count})</span>;
    case 'in_progress': return (
      <span className="text-xs text-blue-600 animate-pulse font-medium">
        Embedding… {pct}% ({v.embedded_count}/{v.term_count})
      </span>
    );
    case 'failed': return <span className="text-xs text-red-500 font-medium">Embedding failed</span>;
    default: return <span className="text-xs text-gray-400">Pending embedding</span>;
  }
}

export function GlossaryDetail() {
  const { clientId, glossaryId } = useParams<{ clientId: string; glossaryId: string }>();
  const { user } = useAuthStore();
  const toast = useToastContext();
  const qc = useQueryClient();
  const isAdmin = user?.role === 'admin';
  const isPM = user?.role === 'project_manager';

  const [tab, setTab] = useState<Tab>('terms');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);

  // New version upload state
  const [showVersionUpload, setShowVersionUpload] = useState(false);
  const [versionFile, setVersionFile] = useState<File | null>(null);
  const [versionSourceCol, setVersionSourceCol] = useState('');
  const [versionChangeNote, setVersionChangeNote] = useState('');
  const versionFileRef = useRef<HTMLInputElement>(null);

  const PAGE_SIZE = 50;

  const { data: glossary, isLoading } = useQuery<GlossaryDetailType>({
    queryKey: ['glossary', clientId, glossaryId],
    queryFn: () => apiClient.getGlossary(clientId!, glossaryId!),
    enabled: !!clientId && !!glossaryId,
    refetchInterval: (q) => {
      const g = q.state.data as GlossaryDetailType | undefined;
      if (!g) return false;
      const hasInProgress = g.versions.some(v => v.embedding_status === 'in_progress' || v.embedding_status === 'pending');
      return hasInProgress ? 5000 : false;
    },
  });

  const { data: termsData, isLoading: termsLoading } = useQuery({
    queryKey: ['glossary-terms', clientId, glossaryId, search, page],
    queryFn: () => apiClient.getGlossaryTerms(clientId!, glossaryId!, { search: search || undefined, page, pageSize: PAGE_SIZE }),
    enabled: !!clientId && !!glossaryId && tab === 'terms',
    placeholderData: (prev) => prev,
  });

  const activateMut = useMutation({
    mutationFn: (versionId: string) => apiClient.activateGlossaryVersion(clientId!, glossaryId!, versionId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['glossary', clientId, glossaryId] });
      qc.invalidateQueries({ queryKey: ['glossaries', clientId] });
      toast.success('Version activated');
    },
    onError: () => toast.error('Failed to activate version'),
  });

  const reembedMut = useMutation({
    mutationFn: (versionId: string) => apiClient.reembedGlossaryVersion(clientId!, glossaryId!, versionId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['glossary', clientId, glossaryId] });
      toast.success('Embedding re-queued');
    },
    onError: () => toast.error('Failed to re-queue embedding'),
  });

  const uploadVersionMut = useMutation({
    mutationFn: () => apiClient.uploadGlossaryVersion(clientId!, glossaryId!, versionFile!, versionSourceCol.trim(), versionChangeNote.trim() || undefined),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['glossary', clientId, glossaryId] });
      setShowVersionUpload(false);
      setVersionFile(null);
      setVersionSourceCol('');
      setVersionChangeNote('');
      toast.success('New version uploaded — embedding in background');
    },
    onError: (err: unknown) => {
      const msg = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ?? 'Upload failed';
      toast.error(msg);
    },
  });

  if (isLoading || !glossary) {
    return (
      <div className="container mx-auto px-4 py-8 max-w-4xl animate-pulse space-y-4">
        <div className="h-8 bg-gray-200 rounded w-1/3" />
        <div className="h-48 bg-gray-200 rounded-xl" />
      </div>
    );
  }

  const activeVersion = glossary.versions.find(v => v.id === glossary.current_version_id);
  const totalPages = termsData ? Math.ceil(termsData.total / PAGE_SIZE) : 1;

  return (
    <div className="container mx-auto px-4 py-8 max-w-4xl space-y-6">
      {/* Header */}
      <div>
        <p className="text-sm text-gray-400 mb-1">
          ← <Link to={`/admin/clients/${clientId}/glossaries`} className="hover:text-blue-600">Glossaries</Link>
        </p>
        <div className="flex items-start justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{glossary.name}</h1>
            {glossary.description && <p className="text-sm text-gray-500 mt-0.5">{glossary.description}</p>}
            <p className="text-xs text-gray-400 mt-1">
              Source: <span className="font-mono">{glossary.source_locale}</span>
              {activeVersion && (
                <> · Active: v{activeVersion.version_number} · {(activeVersion.term_count ?? 0).toLocaleString()} terms</>
              )}
            </p>
            {activeVersion && (
              <div className="mt-1"><EmbeddingPill v={activeVersion} /></div>
            )}
          </div>
          {(isAdmin || isPM) && (
            <button
              onClick={() => setShowVersionUpload(!showVersionUpload)}
              className="px-3 py-1.5 border border-gray-300 text-sm rounded-lg hover:bg-gray-50 shrink-0"
            >
              + New version
            </button>
          )}
        </div>
      </div>

      {/* New version upload panel */}
      {showVersionUpload && (
        <div className="bg-blue-50 border border-blue-200 rounded-xl p-5 space-y-4">
          <h3 className="text-sm font-semibold text-blue-900">Upload new version</h3>
          <div
            className="border-2 border-dashed border-blue-300 rounded-lg p-6 text-center cursor-pointer hover:border-blue-400"
            onClick={() => versionFileRef.current?.click()}
          >
            <input
              ref={versionFileRef}
              type="file"
              accept=".xlsx"
              className="hidden"
              onChange={(e) => setVersionFile(e.target.files?.[0] ?? null)}
            />
            {versionFile
              ? <p className="text-sm font-medium text-gray-900">{versionFile.name}</p>
              : <p className="text-sm text-gray-500">Click to select .xlsx file</p>
            }
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">Source column header *</label>
            <input
              type="text"
              value={versionSourceCol}
              onChange={e => setVersionSourceCol(e.target.value)}
              placeholder="e.g. en_gb"
              className="w-full border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">Change note (optional)</label>
            <input
              type="text"
              value={versionChangeNote}
              onChange={e => setVersionChangeNote(e.target.value)}
              placeholder="e.g. Updated Q2 terms"
              className="w-full border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setShowVersionUpload(false)}
              className="px-3 py-1.5 border border-gray-300 text-sm rounded-lg hover:bg-gray-50"
            >
              Cancel
            </button>
            <button
              type="button"
              disabled={!versionFile || !versionSourceCol.trim() || uploadVersionMut.isPending}
              onClick={() => uploadVersionMut.mutate()}
              className="px-4 py-1.5 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50"
            >
              {uploadVersionMut.isPending ? 'Uploading…' : 'Upload'}
            </button>
          </div>
        </div>
      )}

      {/* Tabs */}
      <div className="border-b border-gray-200">
        <nav className="flex gap-6">
          {(['terms', 'versions'] as Tab[]).map(t => (
            <button
              key={t}
              onClick={() => setTab(t)}
              className={`pb-3 text-sm font-medium border-b-2 transition-colors capitalize ${
                tab === t ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              {t}
              {t === 'versions' && <span className="ml-1 text-xs text-gray-400">({glossary.versions.length})</span>}
            </button>
          ))}
        </nav>
      </div>

      {/* Terms tab */}
      {tab === 'terms' && (
        <div className="space-y-4">
          <input
            type="text"
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1); }}
            placeholder="Search terms…"
            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"
          />

          {termsLoading ? (
            <div className="animate-pulse space-y-2">
              {[1,2,3,4,5].map(i => <div key={i} className="h-10 bg-gray-100 rounded" />)}
            </div>
          ) : termsData?.terms.length === 0 ? (
            <p className="text-sm text-gray-400 text-center py-8">
              {search ? 'No terms match your search' : 'No terms in this glossary yet'}
            </p>
          ) : (
            <>
              <div className="text-xs text-gray-400">{(termsData?.total ?? 0).toLocaleString()} terms total</div>
              <div className="border border-gray-200 rounded-xl overflow-hidden">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 border-b border-gray-200">
                    <tr>
                      <th className="text-left px-4 py-2.5 font-medium text-gray-600 w-1/3">Source term</th>
                      <th className="text-left px-4 py-2.5 font-medium text-gray-600">Translations</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {termsData?.terms.map((term, idx) => (
                      <tr key={idx} className="hover:bg-gray-50">
                        <td className="px-4 py-2.5 font-medium text-gray-900 align-top">{term.source_term}</td>
                        <td className="px-4 py-2.5 text-gray-600">
                          <div className="flex flex-wrap gap-2">
                            {Object.entries(term.translations).slice(0, 6).map(([locale, text]) => (
                              <span key={locale} className="inline-flex items-center gap-1 text-xs bg-gray-100 rounded px-1.5 py-0.5">
                                <span className="font-mono text-gray-400">{locale}</span>
                                <span className="text-gray-700 truncate max-w-[120px]">{text}</span>
                              </span>
                            ))}
                            {Object.keys(term.translations).length > 6 && (
                              <span className="text-xs text-gray-400">+{Object.keys(term.translations).length - 6} more</span>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {totalPages > 1 && (
                <div className="flex items-center justify-between pt-2">
                  <button
                    disabled={page <= 1}
                    onClick={() => setPage(p => p - 1)}
                    className="px-3 py-1 text-sm border rounded disabled:opacity-40"
                  >
                    ← Previous
                  </button>
                  <span className="text-sm text-gray-500">Page {page} of {totalPages}</span>
                  <button
                    disabled={page >= totalPages}
                    onClick={() => setPage(p => p + 1)}
                    className="px-3 py-1 text-sm border rounded disabled:opacity-40"
                  >
                    Next →
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      )}

      {/* Versions tab */}
      {tab === 'versions' && (
        <div className="space-y-3">
          {glossary.versions.map((v) => {
            const isActive = v.id === glossary.current_version_id;
            return (
              <div
                key={v.id}
                className={`rounded-xl border p-4 flex items-start justify-between gap-4 ${
                  isActive ? 'border-blue-300 bg-blue-50' : 'border-gray-200 bg-white'
                }`}
              >
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-sm font-semibold text-gray-900">Version {v.version_number}</span>
                    {isActive && (
                      <span className="text-xs bg-blue-600 text-white px-2 py-0.5 rounded-full font-medium">Active</span>
                    )}
                  </div>
                  <p className="text-xs text-gray-500">
                    {(v.term_count ?? 0).toLocaleString()} terms · uploaded {new Date(v.created_at).toLocaleDateString()}
                  </p>
                  {v.change_note && <p className="text-xs text-gray-400 mt-0.5 italic">"{v.change_note}"</p>}
                  <div className="mt-1"><EmbeddingPill v={v} /></div>
                </div>
                {(isAdmin || isPM) && (
                  <div className="flex gap-2 shrink-0">
                    {v.embedding_status !== 'in_progress' && (
                      <button
                        onClick={() => {
                          if (confirm(`Re-run embedding for version ${v.version_number}? This will reset the current embedding progress.`)) {
                            reembedMut.mutate(v.id);
                          }
                        }}
                        disabled={reembedMut.isPending}
                        className="text-xs px-3 py-1.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                      >
                        ↻ Re-embed
                      </button>
                    )}
                    {!isActive && (
                      <button
                        onClick={() => {
                          if (confirm(`Activate version ${v.version_number}? AI translations will start using this version.`)) {
                            activateMut.mutate(v.id);
                          }
                        }}
                        disabled={activateMut.isPending}
                        className="text-xs px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
                      >
                        Activate
                      </button>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
