"use client";

import * as React from "react";
import {
  ColumnDef,
  ColumnFiltersState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFilteredRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";

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

import { DataTablePaginationFinal } from "./DataTablePaginationFinal";
import { DataTableToolbar } from "./DataTableToolbar";
import { useTranslation } from "react-i18next";
import { usePersistedColumnVisibility } from "@/shared/hooks/usePersistedColumnVisibility";

interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  tableName: string;
  initialColumnVisibility?: VisibilityState;
  extraToolbar?: React.ReactNode;
  toolBarPosition?: "right" | "left" | "center";
  isLoading?: boolean;
  itemCount: number;
  pageIndex: number; // <-- new
  pageSize?: number; // <-- new
  onPageChange: (pageIndex: number) => void; // <-- required
  onPageSizeChange?: (size: number) => void; // <-- new
  nextFunction: () => void;
  prevFunction: () => void;
  refresh?: () => void;
  onGlobalFilterChange?: (value: string) => void;
  /** Hide the toolbar's "Filter <tableName>..." text input. Use when the page
   * already provides its own search/filter UI above the table. */
  hideToolbarFilter?: boolean;
  /** Disable client-side filtering when using server-side filtering */
  disableClientFiltering?: boolean;
}
interface incomingHistory {
  status: string;
  record: { recordTypeKey: string };
  id: string;
  isUrgent?: boolean;
}

export function AdvancedTable<TData, TValue>({
  columns,
  data,
  tableName,
  initialColumnVisibility,
  extraToolbar,
  toolBarPosition = "right",
  isLoading = false,
  itemCount,
  onPageChange,
  onPageSizeChange,
  nextFunction,
  prevFunction,
  pageIndex,
  pageSize = 10,
  refresh,
  onGlobalFilterChange,
  hideToolbarFilter = false,
  disableClientFiltering = false,
}: DataTableProps<TData, TValue>) {
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
    [],
  );
  const [columnVisibility, setColumnVisibility] = usePersistedColumnVisibility(
    tableName,
    {
      letterName: false,
      fileName: false,
      ...(initialColumnVisibility ?? {}),
    },
  );
  const [rowSelection, setRowSelection] = React.useState({});
  const { t } = useTranslation();

  const table = useReactTable({
    data,
    columns,
    pageCount: pageSize > 0 ? Math.ceil(itemCount / pageSize) : 1,
    state: {
      sorting,
      columnVisibility,
      rowSelection,
      columnFilters,
      pagination: {
        pageIndex, // now controlled from props
        pageSize,
      },
    },
    manualPagination: true,
    enableRowSelection: true,
    onRowSelectionChange: setRowSelection,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onColumnVisibilityChange: setColumnVisibility,
    getCoreRowModel: getCoreRowModel(),
    ...(disableClientFiltering
      ? {}
      : { getFilteredRowModel: getFilteredRowModel() }),
    getSortedRowModel: getSortedRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
  });

  return (
    <div className="space-y-4">
      <DataTableToolbar
        table={table}
        tableName={tableName}
        extraToolbar={extraToolbar}
        toolBarPosition={toolBarPosition}
        refreshTable={refresh}
        onGlobalFilterChange={onGlobalFilterChange}
        hideToolbarFilter={hideToolbarFilter}
        disableClientFiltering={disableClientFiltering}
      />

      <div className="rounded-md border dark:border-gray-700 bg-white dark:bg-gray-900 overflow-x-auto font-urbanist custom-scrollbar">
        <Table className="w-full text-base text-gray-700 dark:text-gray-300 font-urbanist">
          <TableHeader className="bg-gray-50 dark:bg-gray-800">
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id} className="dark:border-gray-700">
                {headerGroup.headers.map((header) => (
                  <TableHead
                    key={header.id}
                    className="text-base text-gray-500 dark:text-gray-400 dark:bg-gray-800"
                  >
                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext(),
                        )}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>

          <TableBody>
            {isLoading ? (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="text-center py-6"
                >
                  Loading...
                </TableCell>
              </TableRow>
            ) : table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() && "selected"}
                  className={`
                      transition-colors duration-150
                      ${
                        ((row.original as incomingHistory).isUrgent === true &&
                          tableName === "Pending Records") ||
                        ((row.original as any).action === "inprogress" &&
                          tableName === "My Approval Records")
                          ? "bg-yellow-200 dark:bg-yellow-900/30 hover:bg-yellow-300 dark:hover:bg-yellow-900/50"
                          : "hover:bg-gray-100 dark:hover:bg-gray-800"
                      }
                          ${
                            (((row.original as any).signStatus === "draft" &&
                              tableName === "Collaborations") ||
                              tableName === "Pending Approval Tasks") &&
                            "bg-primary-50 dark:bg-primary-900/20 hover:bg-primary-100 dark:hover:bg-primary-900/30 font-semibold border-l-4 border-l-primary-500 dark:border-l-primary-400"
                          }
                  `}
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id} className="py-4">
                      <div className="max-h-[110px] max-w-[460px] overflow-y-auto overflow-x-auto scrollbar-hidden hover:cursor-pointer custom-scrollbar">
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext(),
                        )}
                      </div>
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="text-center py-6"
                >
                  {t("common.noResult")}
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      {itemCount > pageSize && (
        <DataTablePaginationFinal
          pageIndex={pageIndex}
          pageSize={pageSize}
          itemCount={itemCount}
          onPageChange={onPageChange}
          onPageSizeChange={onPageSizeChange}
          nextFunction={nextFunction}
          prevFunction={prevFunction}
        />
      )}
    </div>
  );
}
