"use client";

import {
  ColumnDef,
  ColumnFiltersState,
  SortingState,
  PaginationState,
  VisibilityState,
  RowSelectionState,
  Updater,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
  FilterFn,
} from "@tanstack/react-table";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/app/shadcn_components/ui/table";


import { useState } from "react";
import { DataTablePagination } from "./propertyTablePagination";
import { rankItem } from "@tanstack/match-sorter-utils";

/* ----------------------------------------
   Optional fuzzy global filter
----------------------------------------- */
const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
  const itemRank = rankItem(String(row.getValue(columnId) ?? ""), value);
  addMeta?.({ itemRank });
  return itemRank.passed;
};

const DEFAULT_PAGINATION: PaginationState = { pageIndex: 0, pageSize: 7 };

interface DataTableProps<TData> {
  columns: ColumnDef<TData, any>[];
  data: TData[];
  onDeleteProperty?: (propertyId: number) => void;
  columnVisibility?: VisibilityState;
  onColumnVisibilityChange?: (updater: Updater<VisibilityState>) => void;
  // Controlled pagination — when omitted the table manages its own pagination state
  pagination?: PaginationState;
  onPaginationChange?: (updater: Updater<PaginationState>) => void;
  // Controlled row selection — when omitted, selection is disabled/uncontrolled
  rowSelection?: RowSelectionState;
  onRowSelectionChange?: (updater: Updater<RowSelectionState>) => void;
}

export default function DataTable<TData extends Record<string, any>>({
  data,
  columns,
  onDeleteProperty,
  columnVisibility = {},
  onColumnVisibilityChange,
  pagination: controlledPagination,
  onPaginationChange: controlledOnPaginationChange,
  rowSelection,
  onRowSelectionChange,
}: DataTableProps<TData>) {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
  const [globalFilter, setGlobalFilter] = useState("");
  const [internalPagination, setInternalPagination] = useState<PaginationState>(DEFAULT_PAGINATION);

  const isControlled = controlledPagination !== undefined;
  const pagination = isControlled ? controlledPagination : internalPagination;
  const onPaginationChange = isControlled ? controlledOnPaginationChange! : setInternalPagination;

  const selectionEnabled = rowSelection !== undefined;

  const table = useReactTable({
    data,
    columns,

    // Only override row identity when selection is in use: the property table
    // needs id-keyed rows so a selection survives pagination + lazy-loaded pages.
    // Other consumers (e.g. the plan table) keep TanStack's default index-based
    // identity untouched. The idless fallback guards a selection-enabled table
    // whose rows happen to lack an id.
    getRowId: selectionEnabled
      ? (row, index) => (row.id != null ? String(row.id) : String(index))
      : undefined,

    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),

    autoResetPageIndex: false,
    enableRowSelection: selectionEnabled,

    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    onPaginationChange,
    onColumnVisibilityChange,
    onRowSelectionChange,

    globalFilterFn: fuzzyFilter,

    state: {
      sorting,
      columnFilters,
      globalFilter,
      pagination,
      columnVisibility,
      rowSelection: rowSelection ?? {},
    },

    meta: {
      onDeleteProperty,
    },
  });

  return (
    <div className="rounded-xl">
      <Table>
        <TableHeader>
          {table.getHeaderGroups().map((headerGroup) => (
            <TableRow key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <TableHead key={header.id} className="h-12 py-2">
                  {header.isPlaceholder
                    ? null
                    : flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                </TableHead>
              ))}
            </TableRow>
          ))}
        </TableHeader>

        <TableBody>
          {table.getRowModel().rows.length ? (
            table.getRowModel().rows.map((row) => (
              <TableRow
                key={row.id}
                data-state={row.getIsSelected() && "selected"}
              >
                {row.getVisibleCells().map((cell) => (
                  <TableCell key={cell.id}>
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell colSpan={columns.length} className="h-24 text-center">
                No results.
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </Table>

      <div className="mb-2">
        <DataTablePagination table={table} />
      </div>
    </div>
  );
}
