"use client";

import * as React from "react";
import {
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getSortedRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { useVirtualizer } from "@tanstack/react-virtual";

import type { ArrayPath, FieldValues } from "react-hook-form";
import type { ColumnDef } from "@tanstack/react-table";

export const FormDataTable = <
  TData,
  TValue,
  // @ts-expect-error - types
  TForm extends FieldValues = TData,
  ArrPath = ArrayPath<TForm>,
>(props: {
  columns: ColumnDef<TData, TValue>[];
  field: ArrPath;
  // @ts-expect-error - types
  fields: TForm[ArrPath];
}) => {
  const [rowSelection, setRowSelection] = React.useState({});

  const table = useReactTable({
    data: props.fields,
    columns: props.columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    onRowSelectionChange: setRowSelection,
    manualPagination: true,
    manualSorting: true,
    manualFiltering: true,
    state: { rowSelection },
  });

  const { rows } = table.getRowModel();

  const parentRef = React.useRef<HTMLDivElement>(null);

  const virtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 32,
    overscan: 5,
  });

  console.log("virtual rows:", virtualizer.getVirtualItems().length);

  return (
    <div className="flex h-full w-full flex-col">
      <p>{table.getRowModel().rows.length} items</p>
      <div
        className="relative flex-1 overflow-scroll rounded-md border-2 border-black"
        ref={parentRef}
      >
        <div style={{ height: `${virtualizer.getTotalSize()}px` }}>
          <table>
            <thead>
              {table.getHeaderGroups().map((headerGroup) => (
                <tr
                  className="h-8 border-b-2 border-black p-0"
                  key={headerGroup.id}
                >
                  {headerGroup.headers.map((header) => {
                    return (
                      <th
                        className="border-r-2 border-black p-0 text-left font-normal last:border-r-0"
                        key={header.id}
                      >
                        {header.isPlaceholder
                          ? null
                          : flexRender(
                              header.column.columnDef.header,
                              header.getContext()
                            )}
                      </th>
                    );
                  })}
                </tr>
              ))}
            </thead>
            <tbody>
              {virtualizer.getVirtualItems().map((virtualRow, index) => {
                const row = rows[virtualRow.index];
                return (
                  <tr
                    className="border-b-2 border-black p-0"
                    key={row?.id}
                    style={{
                      height: `${virtualRow.size}px`,
                      transform: `translateY(${virtualRow.start - index * virtualRow.size}px)`,
                    }}
                  >
                    {row?.getVisibleCells().map((cell) => (
                      <td
                        className="border-r-2 border-black p-0 last:border-r-0"
                        key={cell.id}
                      >
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext()
                        )}
                      </td>
                    ))}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <p>End of table</p>
    </div>
  );
};
