"use client";

import {
  flexRender,
  getCoreRowModel,
  useReactTable,
  ColumnDef,
} from "@tanstack/react-table";

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

import { Recommendation } from "@/app/db/schema/recommendations";
import { Dispatch, SetStateAction, useEffect } from "react";

interface DataTableProps<T extends Recommendation> {
  columns: ColumnDef<T>[];
  data: T[];
  defaultRowIndex: number;
  rowSelection: {
    [x: number]: boolean;
  };
  setRowSelection: Dispatch<
    SetStateAction<{
      [x: number]: boolean;
    }>
  >;
  setSaveButtonDisabled: Dispatch<SetStateAction<boolean>>;
}

export default function RecommendationTable<T extends Recommendation>({
  data,
  columns,
  defaultRowIndex,
  rowSelection,
  setRowSelection,
  setSaveButtonDisabled,
}: DataTableProps<T>) {
  // Initialise the table

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    onRowSelectionChange: setRowSelection,
    enableMultiRowSelection: false,
    enableSubRowSelection: false,
    state: {
      rowSelection,
    },
  });

  // Add a useEffect hook to monitor changes to rowSelection
  // we use the useEffect to perform the side effect of enabling/disabling the save button
  useEffect(() => {
    // Get the keys of the rowSelection object
    const keys = Object.keys(rowSelection);

    // If rowSelection contains keys, get the index of the selected row, otherwise set to -1
    const selectedRowIndex = keys.length > 0 ? parseInt(keys[0], 10) : -1;

    // If the selected row index is different from the default row index, enable the save button
    if (selectedRowIndex !== defaultRowIndex) {
      setSaveButtonDisabled(false);
    } else {
      // If the selected row index is the same as the default row index, disable the save button
      setSaveButtonDisabled(true);
    }
  }, [rowSelection, defaultRowIndex, setSaveButtonDisabled]);

  return (
    <div className="rounded-md border">
      <Table>
        <TableHeader>
          {table.getHeaderGroups().map((headerGroup) => (
            <TableRow key={headerGroup.id}>
              {headerGroup.headers.map((header) => {
                return (
                  <TableHead key={header.id}>
                    {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>
  );
}
