// src/components/backlink/research/research-columns.tsx
"use client";

import type { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import type { ResearchRow } from "@/lib/backlink/research";
import type { BacklinkStatus } from "@/lib/db/domain-schema";
import { DrBadge } from "../dr-badge";
import { EffortBadge, KindBadge } from "../source-badges";

/** Displayed domain strength: cached Ahrefs DR, else the manual DA. */
const resolvedDr = (r: ResearchRow): number | null => r.dr ?? r.da;

const arrIncludesSome = (
  row: { getValue: (id: string) => unknown },
  columnId: string,
  filterValue: string[],
) => {
  if (!filterValue?.length) return true;
  const cell = row.getValue(columnId);
  if (Array.isArray(cell)) return cell.some((v) => filterValue.includes(v));
  return filterValue.includes(cell as string);
};

/** DR sort: nulls grouped at the bottom of the natural ascending order. */
const sortDr = (a: { original: ResearchRow }, b: { original: ResearchRow }) => {
  const x = resolvedDr(a.original) ?? Number.NEGATIVE_INFINITY;
  const y = resolvedDr(b.original) ?? Number.NEGATIVE_INFINITY;
  return x - y;
};

const STATUS_VARIANT: Record<
  BacklinkStatus,
  "secondary" | "default" | "outline"
> = {
  prospect: "secondary",
  planned: "default",
  in_progress: "default",
  live: "outline",
  lost: "outline",
};

const baseColumns: ColumnDef<ResearchRow>[] = [
  {
    id: "select",
    enableGlobalFilter: false,
    enableSorting: false,
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllRowsSelected() ||
          (table.getIsSomeRowsSelected() && "indeterminate")
        }
        onCheckedChange={(v) => table.toggleAllRowsSelected(!!v)}
        aria-label="Tout sélectionner"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(v) => row.toggleSelected(!!v)}
        onClick={(e) => e.stopPropagation()}
        aria-label={`Sélectionner ${row.original.platform}`}
      />
    ),
  },
  {
    id: "source",
    accessorFn: (r) => `${r.platform} ${r.domainNorm}`,
    header: "Source",
    cell: ({ row }) => (
      <div className="flex max-w-[13rem] flex-col">
        <span className="truncate font-medium">{row.original.platform}</span>
        <span className="truncate text-muted-foreground text-xs">
          {row.original.domainNorm}
        </span>
      </div>
    ),
  },
  {
    id: "dr",
    accessorFn: (r) => resolvedDr(r),
    header: "DR",
    enableGlobalFilter: false,
    sortingFn: sortDr,
    cell: ({ row }) => <DrBadge value={resolvedDr(row.original)} />,
  },
  {
    accessorKey: "kind",
    header: "Type",
    enableGlobalFilter: false,
    filterFn: arrIncludesSome,
    cell: ({ row }) => <KindBadge kind={row.original.kind} />,
  },
  {
    accessorKey: "language",
    header: "Langue",
    enableGlobalFilter: false,
    filterFn: (row, _id, v: string) =>
      !v || v === "all" || row.original.language === v,
    cell: ({ row }) => (
      <Badge variant="outline" className="uppercase">
        {row.original.language}
      </Badge>
    ),
  },
  {
    accessorKey: "effort",
    header: "Effort",
    enableGlobalFilter: false,
    cell: ({ row }) => <EffortBadge value={row.original.effort} />,
  },
  {
    accessorKey: "score",
    header: "Score",
    enableGlobalFilter: false,
    cell: ({ row }) => (
      <span className="font-semibold tabular-nums">
        {row.original.score.toFixed(1)}
      </span>
    ),
  },
  {
    id: "footprint",
    accessorKey: "footprint",
    header: "Footprint",
    enableGlobalFilter: false,
    cell: ({ row }) => (
      <span className="inline-flex items-center gap-1.5">
        <span className="tabular-nums">{row.original.footprint}</span>
        {row.original.alert ? (
          <Badge variant="destructive">⚠️ {row.original.footprint} sites</Badge>
        ) : null}
      </span>
    ),
  },
  {
    id: "targeted",
    accessorFn: (r) => r.targetedByCurrent,
    header: "Ciblé",
    enableGlobalFilter: false,
    enableSorting: false,
    // Hide-targeted toggle: any truthy filter value drops targeted rows.
    filterFn: (row, _id, v) => !v || !row.original.targetedByCurrent,
    cell: ({ row }) => {
      const status = row.original.currentStatus;
      if (!row.original.targetedByCurrent || !status)
        return <span className="text-muted-foreground">—</span>;
      return <Badge variant={STATUS_VARIANT[status]}>{status}</Badge>;
    },
  },
];

/** Every column is centered except Source (kept left-aligned). */
const colKey = (c: ColumnDef<ResearchRow>): string | undefined =>
  c.id ?? ("accessorKey" in c ? (c.accessorKey as string) : undefined);

export const researchColumns: ColumnDef<ResearchRow>[] = baseColumns.map((c) =>
  colKey(c) === "source"
    ? c
    : { ...c, meta: { ...c.meta, align: "center" as const } },
);
