'use client';

// OpenCATS-style attachments panel for a candidate: multiple files with
// metadata + history, a primary résumé, upload, delete, set-primary, and a
// signed (private) download link. Used on the candidate detail page.
import { useCallback, useEffect, useRef, useState } from 'react';
import { toast } from 'react-toastify';
import { api } from '@/lib/api';
import { showConfirmDelete } from '@/lib/confirm';

interface Attachment {
  id: number;
  kind: 'resume' | 'cover_letter' | 'other';
  kind_label: string;
  original_filename: string;
  content_type: string;
  size: number;
  is_primary: boolean;
  created_at: string;
  uploaded_by_email: string | null;
  download_url: string | null;
}

const KINDS = [
  { v: 'resume', label: 'Résumé' },
  { v: 'cover_letter', label: 'Cover Letter' },
  { v: 'other', label: 'Other' },
] as const;

function humanSize(n: number): string {
  if (!n) return '—';
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
  return `${(n / 1024 / 1024).toFixed(1)} MB`;
}

export default function CandidateAttachments({ candidateId }: { candidateId: number | string }) {
  const [rows, setRows] = useState<Attachment[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [kind, setKind] = useState<Attachment['kind']>('resume');
  const fileRef = useRef<HTMLInputElement>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const r: any = await api.get(`/candidates/${candidateId}/attachments/`);
      setRows(r?.data ?? []);
    } catch {
      setRows([]);
    } finally {
      setLoading(false);
    }
  }, [candidateId]);

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

  const onUpload = async (files: FileList | null) => {
    if (!files?.length) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('file', files[0]);
      fd.append('kind', kind);
      await api.upload(`/candidates/${candidateId}/attachments/`, fd);
      toast.success('Attachment uploaded');
      await load();
    } catch (e: any) {
      toast.error(e?.message || 'Upload failed');
    } finally {
      setUploading(false);
      if (fileRef.current) fileRef.current.value = '';
    }
  };

  const setPrimary = async (a: Attachment) => {
    try {
      await api.patch(`/candidates/${candidateId}/attachments/${a.id}/`, { is_primary: true });
      await load();
    } catch (e: any) {
      toast.error(e?.message || 'Could not update');
    }
  };

  const remove = async (a: Attachment) => {
    if (!(await showConfirmDelete(`Delete "${a.original_filename}"?`))) return;
    try {
      await api.delete(`/candidates/${candidateId}/attachments/${a.id}/`);
      toast.success('Deleted');
      await load();
    } catch {
      toast.error('Could not delete');
    }
  };

  return (
    <div className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none p-6 shadow-sm h-[224px] flex flex-col">
      <div className="flex items-center justify-between gap-3 flex-wrap mb-4 shrink-0">
        <h3 className="text-sm font-bold text-slate-800 dark:text-white">
          <i className="fa-solid fa-paperclip text-[#405189] mr-2" />Attachments
        </h3>
        <div className="flex items-center gap-2">
          <select value={kind} onChange={(e) => setKind(e.target.value as Attachment['kind'])}
            className="px-2 py-1.5 text-xs border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 focus:outline-none">
            {KINDS.map((k) => <option key={k.v} value={k.v}>{k.label}</option>)}
          </select>
          <input ref={fileRef} type="file" accept=".pdf,.doc,.docx" hidden onChange={(e) => onUpload(e.target.files)} />
          <button onClick={() => fileRef.current?.click()} disabled={uploading}
            className="text-xs px-3 py-1.5 bg-[#405189] text-white font-bold hover:bg-[#334267] transition disabled:opacity-50 cursor-pointer inline-flex items-center gap-1.5">
            <i className={`fa-solid ${uploading ? 'fa-spinner fa-spin' : 'fa-file-arrow-up'}`} />{uploading ? 'Uploading…' : 'Upload'}
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto min-h-0">
      {loading ? (
        <p className="text-xs text-slate-400 py-4 text-center">Loading…</p>
      ) : rows.length === 0 ? (
        <p className="text-xs text-slate-400 py-6 text-center">No attachments yet.</p>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-xs min-w-[620px]">
            <thead>
              <tr className="border-b border-slate-100 dark:border-slate-800">
                {['File', 'Type', 'Size', 'Uploaded by', 'Added', ''].map((h) => (
                  <th key={h} className="text-left py-2 px-2 text-[10px] font-extrabold uppercase tracking-wider text-slate-400">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 dark:divide-slate-800">
              {rows.map((a) => (
                <tr key={a.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition">
                  <td className="py-2.5 px-2 font-bold text-slate-700 dark:text-slate-200">
                    {a.download_url
                      ? <a href={a.download_url} target="_blank" rel="noopener noreferrer" className="text-[#405189] dark:text-indigo-400 hover:underline">{a.original_filename || 'file'}</a>
                      : (a.original_filename || 'file')}
                    {a.is_primary && <span className="ml-2 text-[9px] font-extrabold px-1.5 py-0.5 bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300">PRIMARY</span>}
                  </td>
                  <td className="py-2.5 px-2 text-slate-500">{a.kind_label}</td>
                  <td className="py-2.5 px-2 text-slate-500 whitespace-nowrap">{humanSize(a.size)}</td>
                  <td className="py-2.5 px-2 text-slate-500 truncate max-w-[160px]">{a.uploaded_by_email || '—'}</td>
                  <td className="py-2.5 px-2 text-slate-400 whitespace-nowrap">{a.created_at ? new Date(a.created_at).toLocaleDateString('en-IN') : '—'}</td>
                  <td className="py-2.5 px-2 text-right whitespace-nowrap">
                    {a.kind === 'resume' && !a.is_primary && (
                      <button onClick={() => setPrimary(a)} title="Make primary résumé"
                        className="text-[11px] font-bold text-[#405189] dark:text-indigo-400 hover:underline mr-3 cursor-pointer">Make primary</button>
                    )}
                    <button onClick={() => remove(a)} title="Delete"
                      className="text-rose-600 dark:text-rose-400 hover:text-rose-700 cursor-pointer"><i className="fa-solid fa-trash text-xs" /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
      </div>
    </div>
  );
}
