import {
  Table as ShadcnTable,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
} from "@/components/ui/table";

import style from "./style.module.scss";

import { flexRender, Table } from "@tanstack/react-table";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { memo, useEffect } from "react";

function TanstackTable<T>({
  table,
  onRowClick,
}: {
  table: Table<any>;
  onRowClick?: (data: T) => void;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();

  function setPageParams(key: string, value: string | number) {
    router.push(`${pathname}?${key}=${value}`);
  }

  useEffect(() => {
    const sp = new URLSearchParams(searchParams);
    let offset = table.getState().pagination.pageIndex;
    let limit = table.getState().pagination.pageSize;
    sp.set("limit", limit.toString());
    sp.set("offset", offset.toString());
    router.push(`${pathname}?${sp.toString()}`);
  }, [
    table.getState().pagination.pageIndex,
    table.getState().pagination.pageSize,
  ]);

  // Calculate correct page count - debug the values
  const currentPage = table.getState().pagination.pageIndex + 1;
  const pageSize = table.getState().pagination.pageSize;
  const totalRows = table.getRowCount();
  const totalPages = totalRows > 0 ? Math.ceil(totalRows / pageSize) : 1;
  
  // Debug log to see what values we're getting
  console.log('Pagination Debug:', { currentPage, pageSize, totalRows, totalPages });

  return (
    <div className="p-2">
      <ShadcnTable
        id="tanstack-table"
        className={`${style.table} ${style.scrollable}`}
      >
        <thead className={` ${style.thead}`}>
          {table.getHeaderGroups().map((headerGroup) => (
            <TableRow key={headerGroup.id} className={`${style.tr} `}>
              {headerGroup.headers.map((header) => (
                <TableHead
                  className={`border z-1 flex justify-center ${style.th}`}
                  key={header.id}
                  colSpan={header.colSpan}
                  onClick={header.column.getToggleSortingHandler()}
                >
                  {header.isPlaceholder ? null : (
                    <>
                      {flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                      {header.column.getCanFilter() ? (
                        <div>
                          {/* <Filter column={header.column} table={table} /> */}
                        </div>
                      ) : null}
                      {{
                        asc: " 🔼",
                        desc: " 🔽",
                      }[header.column.getIsSorted() as string] ?? null}
                    </>
                  )}
                </TableHead>
              ))}
            </TableRow>
          ))}
        </thead>

        <TableBody className={`${style.tbody}`}>
          {table?.getRowModel()?.rows?.length > 0 ? (
            table?.getRowModel()?.rows?.map((row) => (
              <TableRow
                className={`${style.tr} `}
                key={row.id}
                onClick={(e) => {
                  onRowClick && onRowClick(row.original);
                }}
              >
                {row.getVisibleCells().map((cell) => (
                  <TableCell
                    className={`border text-center ${style.td}`}
                    key={cell.id}
                  >
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : (
            <TableRow>
              <TableCell
                colSpan={table.getAllColumns().length}
                className="text-center py-8 text-gray-500"
              >
                No results found
              </TableCell>
            </TableRow>
          )}
        </TableBody>
      </ShadcnTable>

      <div className="h-2" />
      {/* Comment out the pagination controls rendering block
      <div className="flex items-center gap-2 text-sm">
        <button
          className="border rounded p-1"
          onClick={() => {
            table.firstPage();
          }}
          disabled={!table.getCanPreviousPage()}
        >
          {"<<"}
        </button>
        <button
          className="border rounded p-1"
          onClick={() => {
            table.previousPage();
          }}
          disabled={!table.getCanPreviousPage()}
        >
          {"<"}
        </button>
        <button
          className="border rounded p-1"
          onClick={() => {
            table.nextPage();
          }}
          disabled={!table.getCanNextPage()}
        >
          {">"}
        </button>
        <button
          className="border rounded p-1"
          onClick={() => {
            table.lastPage();
          }}
          disabled={!table.getCanNextPage()}
        >
          {">>"}
        </button>
        <span className="flex items-center gap-1">
          <div>Page</div>
          <strong>
            {currentPage} of {totalPages}
          </strong>
        </span>
        <span className="flex items-center gap-1">
          | Go to page:
          <input
            type="number"
            defaultValue={currentPage}
            onChange={(e) => {
              const page = e.target.value ? Number(e.target.value) - 1 : 0;
              table.setPageIndex(page);
            }}
            className="border p-1 rounded w-16"
          />
        </span>
        <select
          value={table.getState().pagination.pageSize}
          onChange={(e) => {
            table.setPageSize(Number(e.target.value));
          }}
        >
          {[10, 20, 30, 40, 50].map((pageSize) => (
            <option key={pageSize} value={pageSize}>
              Show {pageSize}
            </option>
          ))}
        </select>
      </div>
      */}
      <br />
    </div>
  );
}

export default memo(TanstackTable);
