// src/components/ui/data-table.tsx
"use client";

import {
  type ColumnDef,
  type ColumnFiltersState,
  type ColumnOrderState,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  type OnChangeFn,
  type PaginationState,
  type RowData,
  type RowSelectionState,
  type SortingState,
  type TableMeta,
  useReactTable,
  type VisibilityState,
} from "@tanstack/react-table";
import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";

declare module "@tanstack/react-table" {
  interface ColumnMeta<TData extends RowData, TValue> {
    align?: "center" | "right";
  }
}

interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  globalFilter?: string;
  columnFilters?: ColumnFiltersState;
  columnVisibility?: VisibilityState;
  rowSelection?: RowSelectionState;
  // Pass-through (TanStack OnChangeFn) so functional updaters chain against the
  // latest state — required for multi-row updates like shift-click range select.
  onRowSelectionChange?: OnChangeFn<RowSelectionState>;
  sorting?: SortingState;
  onSortingChange?: (next: SortingState) => void;
  onRowClick?: (row: TData) => void;
  getRowId?: (row: TData) => string;
  meta?: TableMeta<TData>;
  caption?: string;
  /**
   * When set, enables client-side pagination: adds the pagination row model,
   * seeds `initialState.pagination.pageSize`, and renders a prev/next footer.
   * When omitted, the table renders every row with no pagination (default path
   * unchanged — `getPaginationRowModel` is never wired up).
   */
  pageSize?: number;
  /** When set (with `pageSize`), renders a page-size selector in the controls bar. */
  pageSizeOptions?: number[];
  /** Reports the post-filter rows (column filters + global filter) whenever they change. */
  onFilteredRowsChange?: (rows: TData[]) => void;
  /**
   * Opt-in controlled pagination (with `pageSize` as the seed). When provided,
   * the parent owns the pagination state and can render its own controls.
   */
  pagination?: PaginationState;
  onPaginationChange?: OnChangeFn<PaginationState>;
  /** Opt-out of the built-in pagination controls (parent renders its own). */
  hidePagination?: boolean;
  /**
   * Server-driven mode: `data` is already the filtered/sorted/paginated page
   * from the server — sets `manualFiltering`/`manualSorting`/
   * `manualPagination` so TanStack renders `data` as-is instead of
   * re-filtering/re-sorting/re-slicing it client-side. The default
   * (non-manual) path is unaffected byte-for-byte.
   */
  manual?: boolean;
  /** Opt-in sticky header row (needs a non-clipping container). */
  stickyHeader?: boolean;
  /** Extra classes for the table wrapper (merged over the default border/rounding). */
  containerClassName?: string;
}

export function DataTable<TData, TValue>({
  columns,
  data,
  globalFilter = "",
  columnFilters = [],
  columnVisibility,
  rowSelection = {},
  onRowSelectionChange,
  sorting: sortingProp,
  onSortingChange,
  onRowClick,
  getRowId,
  meta,
  caption,
  pageSize,
  pageSizeOptions,
  onFilteredRowsChange,
  pagination,
  onPaginationChange,
  hidePagination,
  manual,
  stickyHeader,
  containerClassName,
}: DataTableProps<TData, TValue>) {
  const paginated = pageSize !== undefined;
  const [internalSorting, setInternalSorting] = useState<SortingState>([]);
  const sorting = sortingProp ?? internalSorting;
  const [columnOrder, setColumnOrder] = useState<ColumnOrderState>([]);
  const dragId = useRef<string | null>(null);

  const table = useReactTable({
    data,
    columns,
    state: {
      globalFilter,
      columnFilters,
      columnVisibility,
      rowSelection,
      sorting,
      columnOrder,
      // Controlled pagination is opt-in; uncontrolled tables keep their
      // internal state (seeded from `initialState` below).
      ...(pagination ? { pagination } : {}),
    },
    ...(onPaginationChange ? { onPaginationChange } : {}),
    enableRowSelection: true,
    onRowSelectionChange,
    onSortingChange: (updater) => {
      const next = typeof updater === "function" ? updater(sorting) : updater;
      (onSortingChange ?? setInternalSorting)(next);
    },
    onColumnOrderChange: setColumnOrder,
    getRowId,
    getCoreRowModel: getCoreRowModel(),
    // Manual (server-driven) mode: skip the client row-model builders
    // entirely — `manualFiltering/Sorting/Pagination` already make TanStack
    // fall back to rendering `data` as-is, so wiring them would be dead code.
    // Non-manual path (every other table) is unchanged: same options object
    // as before, byte-identical.
    ...(manual
      ? { manualFiltering: true, manualSorting: true, manualPagination: true }
      : {
          getFilteredRowModel: getFilteredRowModel(),
          getSortedRowModel: getSortedRowModel(),
          // Gated: only wired when `pageSize` is provided, so the default
          // path is byte-identical for every other table (no pagination row
          // model / footer).
          ...(paginated
            ? {
                getPaginationRowModel: getPaginationRowModel(),
                initialState: { pagination: { pageSize } },
              }
            : {}),
        }),
    meta,
  });

  // Report the post-filter rows upward (export-respects-filters, ELEVA-52).
  // TanStack memoizes the row model: its identity only changes when data or
  // filters change, so this effect cannot loop.
  const filteredRowModel = table.getFilteredRowModel();
  useEffect(() => {
    onFilteredRowsChange?.(filteredRowModel.rows.map((r) => r.original));
  }, [filteredRowModel, onFilteredRowsChange]);

  // `select` stays pinned first; everything else is reorderable.
  const orderedIds = table.getAllLeafColumns().map((c) => c.id);
  const isMovable = (id: string) => id !== "select";

  function reorder(fromId: string, toId: string) {
    if (fromId === toId || !isMovable(fromId) || !isMovable(toId)) return;
    const from = orderedIds.indexOf(fromId);
    const to = orderedIds.indexOf(toId);
    if (from < 0 || to < 0) return;
    const next = [...orderedIds];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    setColumnOrder(next);
  }

  /** Keyboard reordering: Alt+←/→ shifts a header among its movable peers. */
  function onHeaderKeyDown(e: React.KeyboardEvent, colId: string) {
    if (!e.altKey || (e.key !== "ArrowLeft" && e.key !== "ArrowRight")) return;
    const movable = orderedIds.filter(isMovable);
    const idx = movable.indexOf(colId);
    const target = idx + (e.key === "ArrowLeft" ? -1 : 1);
    if (target < 0 || target >= movable.length) return;
    e.preventDefault();
    reorder(colId, movable[target]);
  }

  const tableEl = (
    <div
      className={cn("overflow-hidden rounded-md border", containerClassName)}
    >
      <Table>
        {caption ? (
          <TableCaption className="sr-only">{caption}</TableCaption>
        ) : null}
        <TableHeader
          className={cn(
            stickyHeader &&
              "sticky top-0 z-10 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80",
          )}
        >
          {table.getHeaderGroups().map((hg) => (
            <TableRow key={hg.id}>
              {hg.headers.map((header) => {
                const sorted = header.column.getIsSorted();
                const colId = header.column.id;
                const movable = isMovable(colId);
                const align = header.column.columnDef.meta?.align;
                const content = header.isPlaceholder
                  ? null
                  : flexRender(
                      header.column.columnDef.header,
                      header.getContext(),
                    );
                return (
                  <TableHead
                    key={header.id}
                    scope="col"
                    aria-sort={
                      sorted === "asc"
                        ? "ascending"
                        : sorted === "desc"
                          ? "descending"
                          : undefined
                    }
                    draggable={movable}
                    onDragStart={
                      movable
                        ? () => {
                            dragId.current = colId;
                          }
                        : undefined
                    }
                    onDragOver={movable ? (e) => e.preventDefault() : undefined}
                    onDrop={
                      movable
                        ? () => {
                            if (dragId.current) reorder(dragId.current, colId);
                            dragId.current = null;
                          }
                        : undefined
                    }
                    className={cn(
                      align === "center" && "text-center",
                      align === "right" && "text-right",
                      movable && "cursor-grab",
                    )}
                    title={
                      movable
                        ? "Glisser pour réordonner · Alt+←/→ au clavier"
                        : undefined
                    }
                  >
                    {header.column.getCanSort() ? (
                      <button
                        type="button"
                        onClick={header.column.getToggleSortingHandler()}
                        onKeyDown={(e) => onHeaderKeyDown(e, colId)}
                        className="-ml-1 inline-flex items-center gap-1 rounded px-1 py-0.5 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                      >
                        {content}
                        {sorted === "asc" ? (
                          <ArrowUpIcon className="size-3.5" aria-hidden />
                        ) : sorted === "desc" ? (
                          <ArrowDownIcon className="size-3.5" aria-hidden />
                        ) : (
                          <ChevronsUpDownIcon
                            className="size-3.5 opacity-40"
                            aria-hidden
                          />
                        )}
                      </button>
                    ) : movable ? (
                      <button
                        type="button"
                        onKeyDown={(e) => onHeaderKeyDown(e, colId)}
                        className="inline-flex rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                      >
                        {content}
                      </button>
                    ) : (
                      content
                    )}
                  </TableHead>
                );
              })}
            </TableRow>
          ))}
        </TableHeader>
        <TableBody>
          {table.getRowModel().rows.length ? (
            table.getRowModel().rows.map((row) => (
              <TableRow
                key={row.id}
                data-state={row.getIsSelected() ? "selected" : undefined}
                onClick={() => onRowClick?.(row.original)}
                className={onRowClick ? "group cursor-pointer" : "group"}
              >
                {row.getVisibleCells().map((cell) => {
                  const align = cell.column.columnDef.meta?.align;
                  return (
                    <TableCell
                      key={cell.id}
                      className={cn(
                        align === "center" && "text-center",
                        align === "right" && "text-right",
                      )}
                    >
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext(),
                      )}
                    </TableCell>
                  );
                })}
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={columns.length} className="h-24 text-center">
                Aucun résultat.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );

  // Default path: render the table exactly as before (no wrapper, no controls).
  // Parents that render their own pagination controls opt out the same way.
  if (!paginated || hidePagination) return tableEl;

  const pageState = table.getState().pagination;
  const controls = (
    <div className="flex items-center justify-between gap-2 px-1 text-muted-foreground text-sm">
      <span>
        Page {pageState.pageIndex + 1} / {table.getPageCount() || 1} ·{" "}
        {table.getFilteredRowModel().rows.length} résultats
      </span>
      <div className="flex items-center gap-2">
        {pageSizeOptions ? (
          <Select
            value={String(pageState.pageSize)}
            onValueChange={(v) => table.setPageSize(Number(v))}
          >
            <SelectTrigger size="sm" className="w-[6rem]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent position="popper">
              {pageSizeOptions.map((n) => (
                <SelectItem key={n} value={String(n)}>
                  {n} / page
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        ) : null}
        <Pagination className="mx-0 w-auto">
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                text="Précédent"
                onClick={() => table.previousPage()}
                aria-disabled={!table.getCanPreviousPage()}
                className={cn(
                  !table.getCanPreviousPage() &&
                    "pointer-events-none opacity-40",
                )}
              />
            </PaginationItem>
            <PaginationItem>
              <PaginationNext
                text="Suivant"
                onClick={() => table.nextPage()}
                aria-disabled={!table.getCanNextPage()}
                className={cn(
                  !table.getCanNextPage() && "pointer-events-none opacity-40",
                )}
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      </div>
    </div>
  );

  return (
    <div className="space-y-2">
      {controls}
      {tableEl}
      {controls}
    </div>
  );
}
