// TODO: Sorting
import React, { useMemo } from "react";

import {
  Table as MuiTable,
  TableContainer as MuiTableContainer,
  TableContainerProps as MUITableContainerProps,
  TableProps as MUITableProps,
} from "@mui/material";

import { TableContext } from "../../contexts/TableContext";

import TablePagination from "./TablePagination";
import { useTableSearchParams } from "./useTableSearchParams";

export interface TableProps extends React.PropsWithChildren {
  pagination?: boolean;
  defaultPage?: number;
  defaultRowsPerPage?: number;
  rowsPerPageOptions?: number[];
  count: number;
  tableProps?: MUITableProps;
  tableContainerProps?: MUITableContainerProps;
}

export const Table: React.FC<TableProps> = ({
  count,
  defaultPage,
  pagination,
  defaultRowsPerPage,
  rowsPerPageOptions,
  children,
  tableProps,
  tableContainerProps,
}) => {
  const searchParams = useTableSearchParams({
    page: defaultPage,
    rowsPerPage: defaultRowsPerPage,
  });

  const contextValues = useMemo(
    () => ({
      count,
      rowsPerPageOptions: rowsPerPageOptions ?? [50, 100, 200],
      ...searchParams,
    }),
    [count, searchParams, rowsPerPageOptions],
  );

  return (
    <MuiTableContainer
      {...tableContainerProps}
      sx={{
        "& .MuiTablePagination-toolbar": { pr: 1.5 },
        "& .MuiTableCell-root:first-child": { pl: 3 },
        "& .MuiTableCell-root:last-child": { pr: 3 },
        ...tableContainerProps?.sx,
      }}
    >
      <TableContext.Provider value={contextValues}>
        <MuiTable {...tableProps}>{children}</MuiTable>

        {pagination && <TablePagination />}
      </TableContext.Provider>
    </MuiTableContainer>
  );
};

export default Table;
