import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { formatDistanceToNow } from 'date-fns';
import { apiClient } from '../../lib/api';
import type { LanguageQCStatus, QueueItem } from '../../types/api';

const STATUS_TABS: { label: string; value: LanguageQCStatus | 'all' }[] = [
  { label: 'All', value: 'all' },
  { label: 'Pending', value: 'pending' },
  { label: 'In Review', value: 'in_review' },
  { label: 'Rejected', value: 'rejected' },
  { label: 'Approved', value: 'approved' },
];

const STATUS_BADGE: Record<LanguageQCStatus, string> = {
  pending: 'bg-gray-100 text-gray-600',
  in_review: 'bg-blue-100 text-blue-700',
  approved: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700',
};

const STATUS_LABEL: Record<LanguageQCStatus, string> = {
  pending: 'Pending',
  in_review: 'In Review',
  approved: 'Approved',
  rejected: 'Rejected',
};

const JOB_STATUS_LABEL: Record<string, string> = {
  pending_qc: 'QC',
  qc_feedback: 'QC Feedback',
  pending_final_review: 'Final Review',
  completed: 'Completed',
  rejected: 'Rejected',
};

function QueueRow({ item }: { item: QueueItem }) {
  const navigate = useNavigate();
  const qcStatus = item.lang_qc_status as LanguageQCStatus;

  return (
    <tr
      className="hover:bg-gray-50 cursor-pointer"
      onClick={() => navigate(`/jobs/${item.job_id}?lang=${item.lang}&tab=vtt`)}
    >
      <td className="px-4 py-3 text-sm font-medium text-gray-900 max-w-xs truncate">
        {item.job_title}
      </td>
      <td className="px-4 py-3">
        <span className="px-2 py-0.5 text-xs font-mono bg-gray-100 rounded uppercase">{item.lang}</span>
      </td>
      <td className="px-4 py-3">
        <span className={`px-2 py-0.5 text-xs rounded-full font-medium ${STATUS_BADGE[qcStatus]}`}>
          {STATUS_LABEL[qcStatus]}
        </span>
      </td>
      <td className="px-4 py-3 text-sm text-gray-500">
        {JOB_STATUS_LABEL[item.job_status] ?? item.job_status}
      </td>
      <td className="px-4 py-3 text-xs text-gray-400">
        {item.assigned_at ? `${formatDistanceToNow(new Date(item.assigned_at))} ago` : '—'}
      </td>
      <td className="px-4 py-3 text-xs text-gray-400">
        {item.reviewed_at ? `${formatDistanceToNow(new Date(item.reviewed_at))} ago` : '—'}
      </td>
      <td className="px-4 py-3">
        <span className="text-xs text-blue-600 hover:underline">Open →</span>
      </td>
    </tr>
  );
}

export function LinguistQueue() {
  const [activeTab, setActiveTab] = useState<LanguageQCStatus | 'all'>('all');

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['linguist-queue', activeTab],
    queryFn: () => apiClient.getMyLanguageQCQueue(activeTab === 'all' ? undefined : activeTab),
    refetchInterval: 30_000,
  });

  const items = data?.items ?? [];

  return (
    <div className="p-6 max-w-6xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-semibold text-gray-900">My QC Queue</h1>
          <p className="text-sm text-gray-500 mt-1">Languages assigned to you for quality control</p>
        </div>
        <button
          onClick={() => refetch()}
          className="text-sm text-gray-500 hover:text-gray-700 border border-gray-300 rounded px-3 py-1"
        >
          Refresh
        </button>
      </div>

      {/* Status tabs */}
      <div className="flex gap-1 mb-4 border-b border-gray-200">
        {STATUS_TABS.map(tab => (
          <button
            key={tab.value}
            onClick={() => setActiveTab(tab.value)}
            className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors -mb-px ${
              activeTab === tab.value
                ? 'border-blue-600 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {isLoading && (
        <div className="animate-pulse space-y-2">
          {[1, 2, 3].map(i => <div key={i} className="h-12 bg-gray-100 rounded" />)}
        </div>
      )}

      {!isLoading && items.length === 0 && (
        <div className="text-center py-16 text-gray-400">
          <p className="text-4xl mb-3">📋</p>
          <p className="text-sm">
            {activeTab === 'all' ? 'No languages assigned to you yet.' : `No languages with status "${activeTab}".`}
          </p>
        </div>
      )}

      {!isLoading && items.length > 0 && (
        <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Job</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Lang</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">QC Status</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Job Status</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Assigned</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Reviewed</th>
                <th className="px-4 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {items.map((item, i) => (
                <QueueRow key={`${item.job_id}:${item.lang}:${i}`} item={item} />
              ))}
            </tbody>
          </table>
          <div className="px-4 py-3 border-t border-gray-200 text-sm text-gray-500">
            {items.length} {items.length === 1 ? 'language' : 'languages'}
          </div>
        </div>
      )}
    </div>
  );
}
