'use client';

import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';

const API = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';

const RESULTS = [
  { value: 'PENDING', label: 'Pending' },
  { value: 'SELECTED', label: 'Selected' },
  { value: 'REJECTED', label: 'Rejected' },
  { value: 'HOLD', label: 'Hold' },
  { value: 'BACKUP', label: 'Backup' },
];

const RESULT_CLS: Record<string, string> = {
  SELECTED: 'bg-emerald-50 text-emerald-700 border-emerald-200',
  REJECTED: 'bg-rose-50 text-rose-700 border-rose-200',
  HOLD: 'bg-amber-50 text-amber-700 border-amber-200',
  BACKUP: 'bg-indigo-50 text-indigo-700 border-indigo-200',
  PENDING: 'bg-slate-100 text-slate-500 border-slate-200',
};

export default function PublicShortlistPage() {
  const { token } = useParams<{ token: string }>();
  const [data, setData] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`${API}/pipeline/shortlist/${token}/`);
      const j = await res.json();
      if (!res.ok || !j.success) throw new Error(j.message || 'Not found');
      setData(j.data);
    } catch (e: any) { setError(e.message || 'Shortlist not available.'); }
    finally { setLoading(false); }
  }, [token]);

  useEffect(() => { load(); }, [load]);

  const update = async (item_id: number, patch: Record<string, unknown>) => {
    try {
      await fetch(`${API}/pipeline/shortlist/${token}/`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ item_id, ...patch }),
      });
      load();
    } catch { /* ignore */ }
  };

  if (loading) return <div className="min-h-screen flex items-center justify-center text-slate-400">Loading shortlist…</div>;
  if (error) return <div className="min-h-screen flex items-center justify-center text-rose-500 font-semibold">{error}</div>;

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-6">
      <div className="max-w-4xl mx-auto">
        <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 p-5 mb-4">
          <div className="text-lg font-extrabold text-[#405189]">TA-ATS</div>
          <h1 className="text-xl font-bold text-slate-900 dark:text-white mt-1">{data.title}</h1>
          <p className="text-sm text-slate-500 mt-0.5">Role: {data.job_title}</p>
          {data.note && <p className="text-xs text-slate-500 mt-2">{data.note}</p>}
          <p className="text-[11px] text-slate-400 mt-2">Review the candidates below. Mark the ones you want for a final interview, add comments, and set the final result.</p>
        </div>

        <div className="space-y-3">
          {data.items.map((it: any) => (
            <div key={it.item_id} className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 p-4">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input type="checkbox" checked={it.picked} onChange={(e) => update(it.item_id, { picked: e.target.checked })} className="accent-[#405189]" />
                      <span className="font-bold text-slate-800 dark:text-white">{it.candidate_name}</span>
                    </label>
                    {it.score != null && <span className="text-[10px] font-bold bg-[#0ab39c]/10 text-[#0ab39c] px-2 py-0.5">Score {it.score}</span>}
                  </div>
                  <p className="text-xs text-slate-500 mt-1">{it.current_role || '—'}{it.current_company ? ` at ${it.current_company}` : ''} · {it.experience || '0'} yrs</p>
                  <p className="text-[11px] text-slate-400 mt-1">{(it.skills || []).slice(0, 12).join(' · ')}</p>
                </div>
                <div className="flex flex-col items-end gap-2 shrink-0">
                  <select value={it.final_result} onChange={(e) => update(it.item_id, { final_result: e.target.value })}
                    className={`border px-2 py-1 text-xs font-bold ${RESULT_CLS[it.final_result] || RESULT_CLS.PENDING}`}>
                    {RESULTS.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}
                  </select>
                </div>
              </div>
              <textarea
                defaultValue={it.customer_comment}
                onBlur={(e) => update(it.item_id, { comment: e.target.value })}
                placeholder="Your comment…"
                className="mt-3 w-full bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 px-3 py-2 text-xs focus:outline-none text-slate-800 dark:text-white"
              />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
