'use client';

import { useRouter } from 'next/navigation';
import type { CallStatus, ScreeningRow } from './types';

const TH_CLS =
  'px-3 py-2.5 text-left text-[10px] font-extrabold uppercase tracking-wider text-slate-500 dark:text-slate-400 whitespace-nowrap';
const TD_CLS = 'px-3 py-3 text-xs font-semibold text-slate-600 dark:text-slate-300 whitespace-nowrap';

const STATUS_BADGES: Record<CallStatus, { cls: string; icon: string; label: string; pulse?: boolean }> = {
  QUEUED: { cls: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300', icon: 'fa-clock', label: 'Queued', pulse: true },
  DIALING: { cls: 'bg-cyan-50 text-cyan-700 dark:bg-cyan-950/40 dark:text-cyan-300', icon: 'fa-phone-volume', label: 'Dialing', pulse: true },
  IN_PROGRESS: { cls: 'bg-indigo-50 text-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-300', icon: 'fa-microphone-lines', label: 'On Call', pulse: true },
  COMPLETED: { cls: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300', icon: 'fa-circle-check', label: 'Completed' },
  NO_ANSWER: { cls: 'bg-amber-50 text-amber-700 dark:bg-amber-950/40 dark:text-amber-300', icon: 'fa-phone-slash', label: 'No Answer' },
  BUSY: { cls: 'bg-orange-50 text-orange-700 dark:bg-orange-950/40 dark:text-orange-300', icon: 'fa-phone-slash', label: 'Busy' },
  CANCELLED: { cls: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300', icon: 'fa-ban', label: 'Cancelled' },
  FAILED: { cls: 'bg-rose-50 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300', icon: 'fa-triangle-exclamation', label: 'Failed' },
};

const REC_BADGES: Record<string, string> = {
  QUALIFIED: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300',
  REVIEW: 'bg-amber-50 text-amber-700 dark:bg-amber-950/40 dark:text-amber-300',
  NOT_QUALIFIED: 'bg-rose-50 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300',
};

function scoreCls(score: number) {
  if (score >= 75) return 'text-emerald-600 dark:text-emerald-400';
  if (score >= 50) return 'text-amber-600 dark:text-amber-400';
  return 'text-rose-600 dark:text-rose-400';
}

interface AIScreeningTableProps {
  rows: ScreeningRow[];
  selected: Set<number>;
  onToggle: (candidateId: number) => void;
  onToggleAll: () => void;
  busyCallId: number | null;
  onTranscript: (callId: number) => void;
  onReport: (callId: number, name: string) => void;
  onRetry: (callId: number) => void;
}

export default function AIScreeningTable({
  rows, selected, onToggle, onToggleAll, busyCallId, onTranscript, onReport, onRetry,
}: AIScreeningTableProps) {
  const router = useRouter();

  if (!rows.length) {
    return (
      <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-12 text-center shadow-sm">
        <i className="fa-solid fa-user-plus text-3xl text-slate-300 dark:text-slate-700 mb-3" />
        <p className="text-sm font-semibold text-slate-600 dark:text-slate-300">No candidates in this JD&apos;s pipeline yet.</p>
        <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">
          Upload CVs or an Excel/CSV list above — imported candidates land here, ready for AI screening.
        </p>
      </div>
    );
  }

  const allSelected = rows.length > 0 && rows.every((r) => selected.has(r.candidate_id));

  return (
    <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none shadow-sm overflow-x-auto">
      <table className="w-full min-w-[1000px]">
        <thead className="bg-slate-50 dark:bg-slate-950 border-b border-slate-200 dark:border-slate-800">
          <tr>
            <th className={`${TH_CLS} w-8`}>
              <input
                type="checkbox"
                checked={allSelected}
                onChange={onToggleAll}
                className="w-3.5 h-3.5 accent-indigo-600 cursor-pointer"
                title="Select all"
              />
            </th>
            <th className={TH_CLS}>Name</th>
            <th className={TH_CLS}>Phone</th>
            <th className={TH_CLS}>Experience</th>
            <th className={TH_CLS}>Stage</th>
            <th className={TH_CLS}>AI Call Status</th>
            <th className={TH_CLS}>AI Score</th>
            <th className={TH_CLS}>Recommendation</th>
            <th className={`${TH_CLS} text-right`}>Actions</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
          {rows.map((r) => {
            const call = r.call;
            const badge = call ? STATUS_BADGES[call.status] : null;
            return (
              <tr key={r.candidate_id} className="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">
                <td className={TD_CLS}>
                  <input
                    type="checkbox"
                    checked={selected.has(r.candidate_id)}
                    onChange={() => onToggle(r.candidate_id)}
                    className="w-3.5 h-3.5 accent-indigo-600 cursor-pointer"
                  />
                </td>
                <td className={TD_CLS}>
                  <span className="font-bold text-slate-800 dark:text-white">{r.name}</span>
                  <span className="block text-[10px] text-slate-400 dark:text-slate-500 font-medium">{r.email}</span>
                </td>
                <td className={TD_CLS}>{r.phone || '—'}</td>
                <td className={TD_CLS}>{r.experience ? `${r.experience} yrs` : 'Fresher'}</td>
                <td className={TD_CLS}>
                  {r.stage ? (
                    <span className="inline-flex px-2 py-0.5 rounded-full text-[10px] font-extrabold bg-indigo-50 text-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-300">
                      {r.stage}
                    </span>
                  ) : '—'}
                </td>
                <td className={TD_CLS}>
                  {badge ? (
                    <span
                      className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-extrabold ${badge.cls}`}
                      title={call?.error_message || undefined}
                    >
                      <i className={`fa-solid ${badge.icon} text-[9px] ${badge.pulse ? 'fa-beat-fade' : ''}`} />
                      {badge.label}
                      {call && call.attempts > 1 && <span className="opacity-70">×{call.attempts}</span>}
                    </span>
                  ) : (
                    <span className="text-slate-400 dark:text-slate-600">Not screened</span>
                  )}
                </td>
                <td className={TD_CLS}>
                  {call?.score !== null && call?.score !== undefined ? (
                    <span className={`font-bold ${scoreCls(call.score)}`}>{call.score}%</span>
                  ) : '—'}
                </td>
                <td className={TD_CLS}>
                  {call?.recommendation ? (
                    <span className={`inline-flex px-2 py-0.5 rounded-full text-[10px] font-extrabold ${REC_BADGES[call.recommendation] || ''}`}>
                      {call.recommendation.replace('_', ' ')}
                    </span>
                  ) : '—'}
                </td>
                <td className={`${TD_CLS} text-right`}>
                  <span className="inline-flex gap-1.5">
                    <button
                      onClick={() => router.push(`/candidates/${r.candidate_id}`)}
                      className="px-2 py-1 rounded-none text-[10px] font-bold text-slate-600 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:bg-slate-600 hover:text-white transition cursor-pointer"
                      title="View candidate"
                    >
                      <i className="fa-solid fa-user" />
                    </button>
                    <button
                      onClick={() => call && onTranscript(call.call_id)}
                      disabled={!call?.has_transcript}
                      className="px-2 py-1 rounded-none text-[10px] font-bold text-indigo-600 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-900/50 hover:bg-indigo-600 hover:text-white transition cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
                      title={call?.has_transcript ? 'View transcript' : 'No transcript yet'}
                    >
                      <i className="fa-solid fa-comment-dots" />
                    </button>
                    <button
                      onClick={() => call && onReport(call.call_id, r.name)}
                      disabled={call?.status !== 'COMPLETED' || busyCallId === call?.call_id}
                      className="px-2 py-1 rounded-none text-[10px] font-bold text-slate-600 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:bg-slate-600 hover:text-white transition cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
                      title={call?.status === 'COMPLETED' ? 'Download screening report (PDF)' : 'Available after the call completes'}
                    >
                      <i className="fa-solid fa-file-pdf" />
                    </button>
                    <button
                      onClick={() => call && onRetry(call.call_id)}
                      disabled={!call || ['QUEUED', 'DIALING', 'IN_PROGRESS'].includes(call.status) || busyCallId === call.call_id}
                      className="px-2 py-1 rounded-none text-[10px] font-bold text-emerald-600 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-900/50 hover:bg-emerald-600 hover:text-white transition cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
                      title={call?.status === 'FAILED' || call?.status === 'NO_ANSWER' ? 'Retry the call' : 'Run the call again'}
                    >
                      <i className={`fa-solid ${busyCallId === call?.call_id ? 'fa-spinner fa-spin' : 'fa-rotate-right'}`} />
                    </button>
                  </span>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
