'use client';

import { useCallback, useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { DataTable } from '@/components/data-table/DataTable';
import { formatDate } from '@/lib/dates';

interface DeletedCandidate {
  id: number;
  full_name: string;
  email: string | null;
  phone_number: string;
  skills: string[];
  fresher: boolean;
  total_experience: number | string | null;
  status: string;
  has_resume: boolean;
  deleted_at: string;
  deleted_by: string | null;
}

interface DeletedCandidatesModalProps {
  open: boolean;
  onClose: () => void;
}

/**
 * Admin-only, view-only list of soft-deleted candidates ("Draft" view).
 * No edit / delete / restore actions — purely informational. Reuses DataTable
 * for search, sorting, pagination, and consistent loading/empty states.
 */
export function DeletedCandidatesModal({ open, onClose }: DeletedCandidatesModalProps) {
  const [rows, setRows] = useState<DeletedCandidate[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = (await api.get('/candidates/deleted/')) as any;
      setRows(res?.data?.data ?? res?.data ?? []);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to load soft-deleted candidates.');
      setRows([]);
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (!open) return null;

  const columns = [
    {
      id: 'srNo',
      header: 'S.No.',
      cell: ({ row, table }: any) => {
        const pageIndex = table.getState().pagination.pageIndex;
        const pageSize = table.getState().pagination.pageSize;
        return <span className="font-semibold text-slate-500 dark:text-slate-400">{pageIndex * pageSize + row.index + 1}</span>;
      },
    },
    {
      accessorKey: 'id',
      header: 'Candidate ID',
      cell: ({ row }: any) => <span className="font-bold text-slate-600 dark:text-slate-300 whitespace-nowrap">#{row.original.id}</span>,
    },
    {
      accessorKey: 'full_name',
      header: 'Name',
      cell: ({ row }: any) => <span className="font-extrabold text-slate-800 dark:text-slate-100 whitespace-nowrap">{row.original.full_name || '—'}</span>,
    },
    {
      accessorKey: 'email',
      header: 'Email',
      cell: ({ row }: any) => <span className="text-slate-600 dark:text-slate-300">{row.original.email || '—'}</span>,
    },
    {
      accessorKey: 'phone_number',
      header: 'Phone',
      cell: ({ row }: any) => <span className="text-slate-600 dark:text-slate-300 whitespace-nowrap">{row.original.phone_number || '—'}</span>,
    },
    {
      id: 'skills',
      header: 'Key Skills',
      cell: ({ row }: any) => {
        const s: string[] = row.original.skills || [];
        return s.length ? (
          <div className="flex flex-wrap items-center gap-1 min-w-[200px] cursor-default" title={s.join(', ')}>
            {s.slice(0, 3).map((x) => <span key={x} className="text-[11px] font-semibold bg-[#405189]/10 text-[#405189] px-2 py-0.5 rounded-none whitespace-nowrap">{x}</span>)}
            {s.length > 3 && <span className="text-[11px] font-bold text-[#405189]">+{s.length - 3} more</span>}
          </div>
        ) : <span className="text-slate-400">—</span>;
      },
    },
    {
      id: 'experience',
      header: 'Experience',
      cell: ({ row }: any) => {
        const c = row.original;
        if (c.fresher) return <span className="text-[10px] font-bold px-2 py-0.5 bg-emerald-500/10 text-emerald-600">Fresher</span>;
        const exp = c.total_experience;
        return <span className="text-slate-600 dark:text-slate-300 whitespace-nowrap">{exp != null && exp !== '' ? `${exp} yr${Number(exp) === 1 ? '' : 's'}` : '—'}</span>;
      },
    },
    {
      accessorKey: 'status',
      header: 'Status',
      cell: ({ row }: any) => <span className="text-[10px] font-bold px-2 py-0.5 bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300 whitespace-nowrap">{row.original.status || '—'}</span>,
    },
    {
      id: 'resume',
      header: 'Resume',
      cell: ({ row }: any) => row.original.has_resume
        ? <span className="text-[10px] font-bold px-2 py-0.5 bg-[#0ab39c]/10 text-[#0ab39c] whitespace-nowrap"><i className="fa-solid fa-check mr-1" />Available</span>
        : <span className="text-[10px] font-bold px-2 py-0.5 bg-slate-100 text-slate-400 dark:bg-slate-800 whitespace-nowrap">None</span>,
    },
    {
      accessorKey: 'deleted_at',
      header: 'Deleted On',
      cell: ({ row }: any) => <span className="text-slate-500 whitespace-nowrap">{formatDate(row.original.deleted_at)}</span>,
    },
    {
      accessorKey: 'deleted_by',
      header: 'Deleted By',
      cell: ({ row }: any) => <span className="text-slate-500 whitespace-nowrap">{row.original.deleted_by || '—'}</span>,
    },
  ];

  return (
    <div className="fixed inset-0 z-[160] flex items-center justify-center p-4">
      <div className="fixed inset-0 bg-slate-950/40 dark:bg-slate-950/80 backdrop-blur-sm" onClick={onClose} />
      <div className="relative z-10 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none shadow-2xl w-full max-w-6xl max-h-[90vh] flex flex-col">
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 dark:border-slate-800 shrink-0">
          <div>
            <h3 className="text-base font-bold text-slate-900 dark:text-white flex items-center gap-2">
              <i className="fa-solid fa-trash-can-arrow-up text-[#405189]" />Inactive Candidates
            </h3>
            <p className="text-xs text-slate-400 mt-0.5">List of Inactive Candidate Records.</p>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-none flex items-center justify-center text-slate-400 hover:text-slate-700 dark:hover:text-white hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer"
            aria-label="Close"
          >
            <i className="fa-solid fa-xmark" />
          </button>
        </div>

        <div className="px-6 py-4 overflow-y-auto flex-1 min-h-0">
          {error ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <i className="fa-solid fa-triangle-exclamation text-rose-500 text-2xl mb-3" />
              <p className="text-sm font-semibold text-slate-700 dark:text-slate-200">{error}</p>
              <button
                onClick={load}
                className="mt-4 bg-[#405189] hover:bg-[#364574] text-white rounded-none px-4 py-2 text-xs font-semibold cursor-pointer transition"
              >
                <i className="fa-solid fa-rotate-right mr-1.5" /> Retry
              </button>
            </div>
          ) : (
            <DataTable
              columns={columns}
              data={rows}
              loading={loading}
              controlledGlobalFilter={search}
              onGlobalFilterChange={setSearch}
              searchPlaceholder="Search by name, email, phone..."
              emptyStateTitle="No soft-deleted candidates found."
              emptyStateDescription="Candidates that are deleted will appear here for reference."
            />
          )}
        </div>
      </div>
    </div>
  );
}
