'use client';
import { useEffect, useState } from 'react';
import SortableTable, { Pagination, SortableTableProps } from './Table';
import { PrismaClient } from '@repo/db';
import { getData } from './pagiantedTableActions';

interface PaginatedTableProps<TData>
  extends Omit<SortableTableProps<TData>, 'data'> {
  prismaModel: keyof PrismaClient;
  rowsPerPage?: number;
}

export function PaginatedTable<TData>({
  prismaModel,
  rowsPerPage = 10,
  ...restProps
}: PaginatedTableProps<TData>) {
  const [data, setData] = useState<TData[]>([]);
  const [page, setPage] = useState(0);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    getData(prismaModel, rowsPerPage, page * rowsPerPage).then((result) => {
      if (result) {
        setData(result.data);
        setTotal(result.total);
      }
    });
  }, [page]);

  return (
    <div className="space-y-4">
      <SortableTable data={data} {...restProps} />
      <Pagination
        totalPages={Math.ceil(total / rowsPerPage)}
        page={page}
        setPage={setPage}
      />
    </div>
  );
}
