Snai3i-MarketPlace / frontend / src / components / DataTable / OrderDataTable.tsx
OrderDataTable.tsx
Raw
import { useState } from 'react';
import {
  ColumnDef,
  SortingState,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
} from '@tanstack/react-table';

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { DataTablePagination } from './DataTablePagination';
import { useSearchParams } from 'react-router-dom';
// import SearchInput from './SearchInput';
import { Button } from '@/components/ui/button';

interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  totalEntries: number;
  isFetching?: boolean;
  clickHandler?: (id: number) => void;
  selectRows: boolean;
  name?: string;
  title: string;
  createBtn?: boolean;
  createClickHandler?: () => void;
}

export function DataTable<TData extends { order_id: number }, TValue>({
  columns,
  data,
  totalEntries,
  isFetching = false,
  clickHandler = () => {},
  createBtn = true,
  name,
  title,
  createClickHandler = () => {},
}: DataTableProps<TData, TValue>) {
  const [searchParams, setSearchParams] = useSearchParams();

  const sort = searchParams.get('sort');
  const [sorting, setSorting] = useState<SortingState>(
    sort ? [{ desc: sort.startsWith('-'), id: sort.replace('-', '') }] : []
  );
  const [rowSelection, setRowSelection] = useState({});

  const pagination = {
    pageIndex: Number(searchParams.get('page')) || 0,
    pageSize: Number(searchParams.get('pageSize')) || 10,
  };

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    state: {
      sorting,
      rowSelection,
      pagination,
    },
    pageCount: Math.ceil(totalEntries / pagination.pageSize),
    onPaginationChange: (updater) => {
      setRowSelection({});
      if (typeof updater !== 'function') return;
      const { pageIndex, pageSize } = updater(pagination);
      setSearchParams((searchParams) => {
        searchParams.set('page', pageIndex.toString());
        searchParams.set('pageSize', pageSize.toString());
        return searchParams;
      });
    },
    onSortingChange: setSorting,
    onRowSelectionChange: setRowSelection,
  });

  return (
    <div className="space-y-4 ">
      <div className="flex items-center">
        <div className="flex flex-1 items-center gap-4">
          {/* <SearchInput placeholder="Filter data..." className="w-72" debounce /> */}
          <span className="text-slate-700 text-[26px] font-semibold">
            {title}
          </span>
        </div>
        <div className="flex gap-4">
          {createBtn && (
            <Button
              size="sm"
              className="flex items-center gap-2 rounded-sm"
              onClick={createClickHandler}
            >
              <span>Create {name}</span>
            </Button>
          )}
        </div>
      </div>
      <div className="rounded-md border border-slate-300">
        <Table>
          <TableHeader className='bg-slate-100 '>
            {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'}
                  className={isFetching ? 'opacity-60' : 'cursor-pointer'}
                  onClick={() => clickHandler(row.original.order_id)}
                >
                  {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>
      <DataTablePagination table={table} />
    </div>
  );
}