'use client';

import { useMemo } from 'react';
import { useRouter } from 'next/navigation';
import type { ColumnDef } from '@tanstack/react-table';
import { DataTable } from '@/components/data-table/DataTable';
import type { ToolbarFilterConfig } from '@/components/data-table/DataTableToolbar';
import type { JobPerformanceRow } from './types';

function uniqueOptions(rows: JobPerformanceRow[], key: 'status' | 'client') {
  const set = new Set<string>();
  rows.forEach((r) => { if (r[key]) set.add(r[key]); });
  return [...set].sort().map((v) => ({ label: v, value: v }));
}

export default function OverallJobPerformanceTable({ rows }: { rows: JobPerformanceRow[] }) {
  const router = useRouter();

  const columns = useMemo<ColumnDef<JobPerformanceRow>[]>(() => [
    { accessorKey: 'jd_id', header: 'JD ID', cell: ({ getValue }) => `#${getValue()}` },
    {
      accessorKey: 'job_title',
      header: 'Job Title',
      cell: ({ row }) => (
        <div>
          <span className="font-bold text-slate-800 dark:text-white">{row.original.job_title}</span>
          {row.original.department && (
            <span className="block text-[10px] text-slate-400 dark:text-slate-500 font-medium">{row.original.department}</span>
          )}
        </div>
      ),
    },
    { accessorKey: 'client', header: 'Client', filterFn: 'equalsString', cell: ({ getValue }) => (getValue() as string) || '—' },
    {
      id: 'recruiters',
      accessorFn: (r) => r.assigned_recruiters.join(', '),
      header: 'Recruiters',
      enableSorting: false,
      cell: ({ getValue }) => {
        const v = getValue() as string;
        return <span className="block max-w-[180px] truncate" title={v}>{v || '—'}</span>;
      },
    },
    { accessorKey: 'total_candidates', header: 'Candidates' },
    { accessorKey: 'interview_count', header: 'Interviews' },
    {
      accessorKey: 'hired_count',
      header: 'Hired',
      cell: ({ getValue }) => {
        const n = getValue() as number;
        return <span className={n > 0 ? 'text-emerald-600 dark:text-emerald-400 font-bold' : ''}>{n}</span>;
      },
    },
    { accessorKey: 'average_score', header: 'Avg Score', cell: ({ getValue }) => (getValue() ? `${getValue()}%` : '—') },
    {
      accessorKey: 'status',
      header: 'Status',
      filterFn: 'equalsString',
      cell: ({ getValue }) => (
        <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-extrabold bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300">
          <span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
          {(getValue() as string) || '—'}
        </span>
      ),
    },
    {
      id: 'actions',
      header: () => <div className="text-right">Actions</div>,
      enableSorting: false,
      enableHiding: false,
      cell: ({ row }) => (
        <div className="flex items-center justify-end gap-1.5">
          <button
            onClick={() => router.push(`/jobs/${row.original.jd_id}/pipeline`)}
            className="px-2.5 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 dark:hover:bg-indigo-600 transition cursor-pointer"
            title="Open this JD's pipeline"
          >
            <i className="fa-solid fa-diagram-project mr-1" />
            Pipeline
          </button>
          <button
            onClick={() => router.push('/candidates')}
            className="px-2.5 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 dark:hover:bg-slate-600 transition cursor-pointer"
            title="Browse candidates"
          >
            <i className="fa-solid fa-users mr-1" />
            Candidates
          </button>
        </div>
      ),
    },
  ], [router]);

  const filters = useMemo<ToolbarFilterConfig[]>(() => [
    { columnId: 'status', title: 'Status', options: uniqueOptions(rows, 'status') },
    { columnId: 'client', title: 'Client', options: uniqueOptions(rows, 'client') },
  ], [rows]);

  return (
    <DataTable
      columns={columns}
      data={rows}
      compact
      collapsibleFilters
      enableColumnVisibility
      filters={filters}
      exportConfig={{ fileName: 'job_performance' }}
      searchPlaceholder="Search jobs…"
      emptyStateTitle="No active job descriptions found"
      emptyStateDescription="Publish a JD to see its hiring performance here."
    />
  );
}
