import { useState, useMemo } 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 Progress', value: 'in_progress' },
  { label: 'Pending Review', value: 'pending_review' },
  { label: 'In Review', value: 'in_review' },
  { label: 'Approved', value: 'approved' },
  { label: 'Rejected', value: 'rejected' },
];

const STATUS_BADGE: Record<LanguageQCStatus, string> = {
  pending: 'bg-gray-100 text-gray-600',
  in_progress: 'bg-yellow-100 text-yellow-700',
  pending_review: 'bg-orange-100 text-orange-700',
  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_progress: 'In Progress',
  pending_review: 'Pending Review',
  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 SortArrow({ active, dir }: { active: boolean; dir: 'asc' | 'desc' }) {
  if (!active) return <span className="ml-1 text-gray-300">↕</span>;
  return <span className="ml-1">{dir === 'asc' ? '↑' : '↓'}</span>;
}

function QueueRow({ item, role }: { item: QueueItem; role: 'linguist' | 'reviewer' }) {
  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] ?? 'bg-gray-100 text-gray-600'}`}>
          {STATUS_LABEL[qcStatus] ?? 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>
      {role === 'reviewer' && (
        <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>
  );
}

interface LinguistQueueProps {
  /** Lock the queue to a specific role (hides the role toggle). */
  defaultRole?: 'linguist' | 'reviewer';
}

export function LinguistQueue({ defaultRole }: LinguistQueueProps = {}) {
  const [activeRole, setActiveRole] = useState<'linguist' | 'reviewer'>(defaultRole ?? 'linguist');
  const [activeTab, setActiveTab] = useState<LanguageQCStatus | 'all'>('all');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc');

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

  const items = useMemo(() => {
    const raw = data?.items ?? [];
    return [...raw].sort((a, b) => {
      const ta = a.assigned_at ? new Date(a.assigned_at).getTime() : 0;
      const tb = b.assigned_at ? new Date(b.assigned_at).getTime() : 0;
      return sortDir === 'asc' ? ta - tb : tb - ta;
    });
  }, [data, sortDir]);

  const toggleSort = () => setSortDir(d => (d === 'asc' ? 'desc' : 'asc'));

  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">
            {defaultRole === 'reviewer' ? 'Reviewer Queue' : '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()}
          disabled={isFetching}
          className="text-sm text-gray-500 hover:text-gray-700 border border-gray-300 rounded px-3 py-1 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
        >
          {isFetching && (
            <svg className="animate-spin h-3 w-3" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          )}
          {isFetching ? 'Refreshing…' : 'Refresh'}
        </button>
      </div>

      {/* Role toggle — hidden when role is locked */}
      {!defaultRole && (
        <div className="flex gap-2 mb-5">
          {(['linguist', 'reviewer'] as const).map(role => (
            <button
              key={role}
              onClick={() => { setActiveRole(role); setActiveTab('all'); }}
              className={`px-4 py-1.5 text-sm font-medium rounded-full border transition-colors ${
                activeRole === role
                  ? 'bg-blue-600 border-blue-600 text-white'
                  : 'border-gray-300 text-gray-600 hover:border-gray-400 hover:text-gray-800'
              }`}
            >
              As {role}
            </button>
          ))}
        </div>
      )}

      {/* Status tabs */}
      <div className="flex gap-1 mb-4 border-b border-gray-200 overflow-x-auto">
        {STATUS_TABS.map(tab => (
          <button
            key={tab.value}
            onClick={() => setActiveTab(tab.value)}
            className={`px-3 py-2 text-sm font-medium border-b-2 transition-colors -mb-px whitespace-nowrap ${
              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 as ${activeRole} 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 cursor-pointer select-none hover:text-gray-700"
                  onClick={toggleSort}
                >
                  Assigned <SortArrow active dir={sortDir} />
                </th>
                {activeRole === 'reviewer' && (
                  <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} role={activeRole} />
              ))}
            </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>
  );
}
