'use client';

import { useMemo } from 'react';
import type { ColumnDef } from '@tanstack/react-table';
import { DataTable } from '@/components/data-table/DataTable';
import type { ToolbarFilterConfig } from '@/components/data-table/DataTableToolbar';
import type { StageBreakdown, StageCount } from './types';

const OUTCOME_BADGE: Record<string, string> = {
  WON: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300',
  LOST: 'bg-rose-50 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300',
  IN_PROGRESS: 'bg-blue-50 text-blue-700 dark:bg-blue-950/40 dark:text-blue-300',
};

const OUTCOME_LABEL: Record<string, string> = {
  WON: 'Won',
  LOST: 'Lost',
  IN_PROGRESS: 'In Progress',
};

export default function StageBreakdownTable({ data }: { data: StageBreakdown }) {
  const columns = useMemo<ColumnDef<StageCount>[]>(() => [
    { accessorKey: 'stage', header: 'Stage', cell: ({ getValue }) => (
      <span className="font-bold text-slate-800 dark:text-white">{(getValue() as string) || '—'}</span>
    ) },
    { accessorKey: 'code', header: 'Code', cell: ({ getValue }) => (getValue() as string) || '—' },
    {
      accessorKey: 'outcome',
      header: 'Outcome',
      filterFn: 'equalsString',
      cell: ({ getValue }) => {
        const v = getValue() as string;
        return <span className={`inline-flex px-2 py-0.5 rounded-full text-[10px] font-extrabold ${OUTCOME_BADGE[v] || ''}`}>{OUTCOME_LABEL[v] || v}</span>;
      },
    },
    { accessorKey: 'count', header: 'Candidates', cell: ({ getValue }) => (getValue() as number).toLocaleString() },
    { accessorKey: 'percentage', header: '% of Total', cell: ({ getValue }) => `${getValue()}%` },
  ], []);

  const filters = useMemo<ToolbarFilterConfig[]>(() => [
    {
      columnId: 'outcome',
      title: 'Outcome',
      options: [
        { label: 'In Progress', value: 'IN_PROGRESS' },
        { label: 'Won', value: 'WON' },
        { label: 'Lost', value: 'LOST' },
      ],
    },
  ], []);

  return (
    <DataTable
      columns={columns}
      data={data.stages}
      compact
      collapsibleFilters
      enableColumnVisibility
      filters={filters}
      exportConfig={{ fileName: 'stage_breakdown' }}
      searchPlaceholder="Search stages…"
      emptyStateTitle="No pipeline stages"
      emptyStateDescription="Assign candidates to job descriptions to see the stage breakdown."
    />
  );
}
