"use client";

import * as React from "react";
import {
  ColumnDef,
  ColumnFiltersState,
  SortingState,
  VisibilityState,
  flexRender,
  getCoreRowModel,
  getFacetedRowModel,
  getFacetedUniqueValues,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import {
  Table as ShadcnTable,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { DataTablePaginationFinal } from "@/shared/common/ui/table/DataTablePaginationFinal";
import { DataTableToolbar } from "./dataTableToolbar";
import { useTranslation } from "react-i18next";
import { usePersistedColumnVisibility } from "@/shared/hooks/usePersistedColumnVisibility";

interface CCIncomingRecord {
  content: {
    ccs: { hasSeen: boolean }[];
  }[];
}

interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  tableName: string;
  initialColumnVisibility?: VisibilityState;
  totalCount?: number;
  pagination?: {
    pageIndex: number;
    pageSize: number;
  };
  setPagination?: (pagination: { pageIndex: number; pageSize: number }) => void;
  extraToolbar?: React.ReactNode;
  toolBarPosition?: "right" | "left" | "center";
  refresh?: () => void;
}

export function DataTable<TData, TValue>({
  columns,
  data,
  initialColumnVisibility,
  totalCount,
  pagination = { pageIndex: 0, pageSize: 10 },
  setPagination,
  tableName,
  toolBarPosition,
  refresh,
  extraToolbar,
}: DataTableProps<TData, TValue>) {
  const [sorting, setSorting] = React.useState<SortingState>([]);
  const { t } = useTranslation();
  const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
    [],
  );
  const [columnVisibility, setColumnVisibility] = usePersistedColumnVisibility(
    tableName,
    {
      letterName: false,
      fileName: false,
      ...(initialColumnVisibility ?? {}),
    },
  );
  const [rowSelection, setRowSelection] = React.useState({});

  // Calculate pageCount safely
  const safeTotalCount = totalCount ?? 0;
  const pageSize = pagination?.pageSize ?? 10;
  const pageCount = Math.max(Math.ceil(safeTotalCount / pageSize), 1);

  const table = useReactTable({
    data,
    columns,
    manualPagination: true,
    pageCount,
    state: {
      pagination,
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
    },
    onPaginationChange: React.useCallback(
      (updater: any) => {
        const newPagination =
          typeof updater === "function" ? updater(pagination) : updater;

        if (setPagination) {
          setPagination({
            pageIndex: newPagination.pageIndex,
            pageSize: newPagination.pageSize,
          });
        }
      },
      [pagination, setPagination],
    ),
    enableRowSelection: true,
    onRowSelectionChange: setRowSelection,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onColumnVisibilityChange: setColumnVisibility,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
  });

  return (
    <div className="space-y-2 md:space-y-4">
      <DataTableToolbar
        table={table}
        tableName={tableName}
        extraToolbar={extraToolbar}
        toolBarPosition={toolBarPosition}
        refreshTable={refresh}
      />
      {/* Table container with horizontal scroll for mobile */}
      {/* Table container with horizontal scroll */}
      <div className="overflow-x-auto w-full custom-scrollbar">
        <div className="rounded-md border dark:border-gray-700 min-w-max bg-white dark:bg-gray-900 custom-scrollbar">
          <ShadcnTable
            className="w-full text-gray-700 dark:text-gray-300"
            style={{ tableLayout: "auto" }}
          >
            <TableHeader className="bg-gray-50 dark:bg-gray-800">
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <TableHead
                      key={header.id}
                      className="whitespace-nowrap px-2 md:px-4 py-2 text-left text-base font-medium text-gray-500 dark:text-gray-400"
                    >
                      {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"}
                    className={`${
                      (tableName === "CC Incoming Records" &&
                        !(row.original as CCIncomingRecord)?.content?.[0]
                          ?.ccs?.[0]?.hasSeen) ||
                      (row.original as any)?.status === "draft" ||
                      (row.original as any)?.incomingInstances?.[0]?.status ===
                        "draft" ||
                      (row.original as any)?.content?.[0]?.ccs?.[0]?.hasSeen ===
                        false
                        ? "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"
                        : "hover:bg-gray-50 dark:hover:bg-gray-800/50"
                    }`}
                  >
                    {row.getVisibleCells().map((cell) => (
                      <TableCell
                        key={cell.id}
                        className="whitespace-nowrap px-2 md:px-4 py-2 text-base"
                      >
                        <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="h-16 md:h-24 text-center text-base"
                  >
                    {t("common.noResult")}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </ShadcnTable>
        </div>
      </div>

      {/* Pagination only when more than one page */}
      {safeTotalCount > pageSize && (
        <div className="px-2">
          <DataTablePaginationFinal table={table} itemCount={safeTotalCount} />
        </div>
      )}
    </div>
  );
}
