import React from 'react';
import { Table, TableBody, Box, CircularProgress, TableRow, TableCell } from '@mui/material';
import TableHeadCustom from '@/shared/components/table/table-head-custom';
import TableNoData from '@/shared/components/table/table-no-data';
import TablePaginationCustom from '@/shared/components/table/table-pagination-custom';
import { TableColumn } from '@/shared/types/common';
import { SxProps, Theme } from '@mui/material/styles';
import { StyledTableContainer } from '@/shared/theme/css';
import ConditionalComponent from './ConditionalComponent';

interface GenericTableProps<T> {
  filteredData: T[];
  table: ReturnType<typeof import('@/shared/components/table/use-tablets').default>;
  tableHead: TableColumn[];
  notFound: boolean;
  filters: Record<string, { value: string; condition: string }>;
  onFilterChange: (key: string, value: string, condition: string) => void;
  renderRow: (row: T) => React.ReactNode;
  sx?: SxProps<Theme>;
  isTrajetTable?: boolean;
  fixedHeight?: string;
  isWithoutTabs?: boolean;
  isDrawer?: boolean;
  onPageChange?: (event: React.MouseEvent<HTMLButtonElement> | null, page: number) => void;
  page?: number;
  onRowsPerPageChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  rowsPerPage?: number;
  count?: number;
  sortBy?: string;
  sortDirection?: 'asc' | 'desc';
  loading?: boolean;
}

export default function TableManager<T extends { id: string }>({
  filteredData,
  table,
  tableHead,
  notFound,
  filters,
  onFilterChange,
  renderRow,
  sx,
  isTrajetTable,
  isWithoutTabs,
  fixedHeight,
  isDrawer,
  onPageChange,
  page,
  onRowsPerPageChange,
  rowsPerPage,
  count,
  sortBy,
  sortDirection,
  loading,
}: GenericTableProps<T>) {
  const isEmpty = !Array.isArray(filteredData) || filteredData.length === 0;

  return (
    <>
      <Box sx={{ flexGrow: 1, overflow: 'hidden' }}>
        <StyledTableContainer
          sx={{
            maxHeight: fixedHeight || (isTrajetTable ? 'calc(100vh - 486px)' : '100%'),
            backgroundColor: 'transparent',
            position: 'relative',
            overflow: 'auto',
            '.MuiTableCell-root': {
              fontSize: isDrawer
                ? '12px'
                : {
                    xs: '11px',
                    md: '12px',
                    lg: '13px',
                    xl: '14px',
                  },
            },
          }}
        >
          <Table stickyHeader size={table.dense ? 'small' : 'medium'}>
            <TableHeadCustom
              order={sortDirection ?? table.order}
              orderBy={sortBy ?? table.orderBy}
              headLabel={tableHead.filter(
                (column) => column.id !== 'isActive' && column.id !== 'isArchive'
              )}
              onSort={table.onSort}
              filters={filters}
              onFilters={onFilterChange}
              isTrajetTable={isTrajetTable}
              isWithoutTabs={isWithoutTabs}
              sx={sx}
            />

            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={tableHead.length + 1} align="center" sx={{ py: 3 }}>
                    <CircularProgress size={48} />
                  </TableCell>
                </TableRow>
              ) : (
                <>
                  {filteredData.map(renderRow)}
                  <TableNoData notFound={isEmpty} colSpan={tableHead.length + 1} />
                </>
              )}
            </TableBody>
          </Table>
        </StyledTableContainer>
      </Box>
      <ConditionalComponent isValid={!isTrajetTable}>
        <Box sx={{ flexGrow: 0 }}>
          <TablePaginationCustom
            count={count ?? filteredData.length}
            page={page ?? table.page}
            rowsPerPage={rowsPerPage ?? table.rowsPerPage}
            onPageChange={onPageChange ?? table.onChangePage}
            onRowsPerPageChange={onRowsPerPageChange ?? table.onChangeRowsPerPage}
            dense={table.dense}
            onChangeDense={isDrawer ? undefined : table.onChangeDense}
          />
        </Box>
      </ConditionalComponent>
    </>
  );
}
