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

function statusBadge(status: string) {
  return status === 'active'
    ? 'bg-green-100 text-green-700'
    : 'bg-gray-100 text-gray-500';
}

function embeddingBadge(g: import('../../../types/api').Glossary) {
  const status = g.current_version_embedding_status;
  const pct = g.current_version_term_count && g.current_version_term_count > 0
    ? Math.round(((g.current_version_embedded_count ?? 0) / g.current_version_term_count) * 100)
    : 0;
  switch (status) {
    case 'done': return <span className="text-xs text-green-600">Embedded ✓ ({g.current_version_term_count?.toLocaleString()})</span>;
    case 'in_progress': return <span className="text-xs text-blue-600 animate-pulse">Embedding… {pct}%</span>;
    case 'failed': return <span className="text-xs text-red-500">Embed failed</span>;
    case 'pending': return <span className="text-xs text-gray-400">Pending embed</span>;
    default: return null;
  }
}

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

  const { data: glossaries = [], isLoading } = useQuery<Glossary[]>({
    queryKey: ['glossaries', clientId],
    queryFn: () => apiClient.getGlossaries(clientId!),
    enabled: !!clientId,
    refetchInterval: (q) => {
      const data = q.state.data;
      return Array.isArray(data) ? 5000 : false;
    },
  });

  const archiveMut = useMutation({
    mutationFn: (id: string) => apiClient.archiveGlossary(clientId!, id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['glossaries', clientId] });
      toast.success('Glossary archived');
    },
    onError: () => toast.error('Failed to archive glossary'),
  });

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-8 max-w-4xl animate-pulse space-y-3">
        {[1, 2].map(i => <div key={i} className="h-16 bg-gray-200 rounded-xl" />)}
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-4xl space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm text-gray-400 mb-1">
            ← <Link to={`/admin/clients/${clientId}`} className="hover:text-blue-600">Client</Link>
          </p>
          <h1 className="text-2xl font-bold text-gray-900">Glossaries</h1>
        </div>
        {(isAdmin || isPM) && (
          <Link
            to={`/admin/clients/${clientId}/glossaries/upload`}
            className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700"
          >
            + Upload glossary
          </Link>
        )}
      </div>

      {glossaries.length === 0 ? (
        <div className="text-center py-16 text-gray-400">
          <p className="text-lg mb-2">No glossaries yet</p>
          {(isAdmin || isPM) && (
            <Link to={`/admin/clients/${clientId}/glossaries/upload`} className="text-blue-500 hover:underline text-sm">
              Upload the first glossary
            </Link>
          )}
        </div>
      ) : (
        <div className="space-y-3">
          {glossaries.map((g) => (
            <div key={g.id} className="bg-white rounded-xl border border-gray-200 p-5 flex items-start justify-between gap-4">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1">
                  <Link
                    to={`/admin/clients/${clientId}/glossaries/${g.id}`}
                    className="text-base font-semibold text-gray-900 hover:text-blue-600 truncate"
                  >
                    {g.name}
                  </Link>
                  <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${statusBadge(g.status)}`}>
                    {g.status}
                  </span>
                </div>
                {g.description && <p className="text-sm text-gray-500 mb-1 truncate">{g.description}</p>}
                <p className="text-xs text-gray-400">
                  Source: <span className="font-mono">{g.source_locale}</span>
                  {' · '}Created {new Date(g.created_at).toLocaleDateString()}
                </p>
              </div>
              <div className="flex items-center gap-4 shrink-0">
                <div className="text-right text-xs text-gray-400">
                  {g.current_version_id ? embeddingBadge(g) : null}
                </div>
                {isAdmin && g.status === 'active' && (
                  <button
                    onClick={() => {
                      if (confirm('Archive this glossary? It will no longer be used for AI translations.')) {
                        archiveMut.mutate(g.id);
                      }
                    }}
                    className="text-xs text-red-500 hover:text-red-700"
                  >
                    Archive
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
