"use client";

import {
  ColumnDef,
  ColumnFiltersState,
  SortingState,
  PaginationState,
  VisibilityState,
  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;
}

export default function DataTable<TData extends Record<string, any>>({
  data,
  columns,
  onDeleteProperty,
  columnVisibility = {},
  onColumnVisibilityChange,
  pagination: controlledPagination,
  onPaginationChange: controlledOnPaginationChange,
}: 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 table = useReactTable({
    data,
    columns,

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

    autoResetPageIndex: false,

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

    globalFilterFn: fuzzyFilter,

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

    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>
  );
}
