import {
  Box,
  Button,
  IconButton,
  Select,
  SelectChangeEvent,
  Typography,
  MenuItem,
  Switch,
  FormControlLabel,
} from '@mui/material';
import { SxProps, Theme } from '@mui/material/styles';
import { TablePaginationProps } from '@mui/material/TablePagination';
import FontAwesome from '../fontawesome';
import { faAngleLeft, faAngleRight, faAnglesLeft, faAnglesRight } from '@fortawesome/free-solid-svg-icons';
import { activeButtonStyle, buttonStyle, pointStyle } from './styles';
import { StyledMenuItem } from '@/shared/theme/css';

type Props = {
  dense?: boolean;
  onChangeDense?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  onRowsPerPageChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
  sx?: SxProps<Theme>;
};
const rowsPerPageOptions = [5,10,20,30,50]
export default function TablePaginationCustom({
  dense,
  onChangeDense,
  onRowsPerPageChange,
  sx,
  ...other
}: Props & TablePaginationProps) {
  const { count, page, rowsPerPage, onPageChange } = other;
  const totalPages = Math.ceil(count / rowsPerPage);

  const handlePageChange = (newPage: number) => (event: React.MouseEvent<HTMLButtonElement>) => {
    if (onPageChange) onPageChange(event, newPage);
  };

  const handleRowsPerPageChange = (event: SelectChangeEvent<number>) => {
    if (onRowsPerPageChange) {
      onRowsPerPageChange({
        target: { value: event.target.value },
      } as React.ChangeEvent<HTMLInputElement>);
    }
  };

  const renderNavigationButton = (type: 'first' | 'prev' | 'next' | 'last', isDisabled: boolean, newPage: number, icon: any) => (
    <IconButton
      sx={buttonStyle}
      onClick={handlePageChange(newPage)}
      disabled={isDisabled}
      aria-label={`${type} page`}
    >
      <FontAwesome width={12} icon={icon} />
    </IconButton>
  );

  const renderPageNumbers = () => {
    const items = [];
    const showEllipsisStart = page > 2;
    const showEllipsisEnd = page < totalPages - 3;

    if (showEllipsisStart) {
      items.push(renderPageButton(0));
      items.push(<Box key="start-ellipsis" component="span" sx={pointStyle}>...</Box>);
    }

    for (let i = Math.max(0, page - 1); i <= Math.min(totalPages - 1, page + 1); i++) {
      items.push(renderPageButton(i));
    }

    if (showEllipsisEnd) {
      items.push(<Box key="end-ellipsis" component="span" sx={pointStyle}>...</Box>);
      items.push(renderPageButton(totalPages - 1));
    }

    return items;
  };

  const renderPageButton = (pageIndex: number) => (
    <Button
      key={pageIndex}
      onClick={handlePageChange(pageIndex)}
      sx={page === pageIndex ? activeButtonStyle : buttonStyle}
    >
      {pageIndex + 1}
    </Button>
  );

  return (
    <Box sx={{ position: 'relative', ...sx }}>
      

      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          py: 1,
        }}
      >
        {renderNavigationButton('first', page === 0, 0, faAnglesLeft)}
        {renderNavigationButton('prev', page === 0, page - 1, faAngleLeft)}
        {renderPageNumbers()}
        {renderNavigationButton('next', page === totalPages - 1, page + 1, faAngleRight)}
        {renderNavigationButton('last', page === totalPages - 1, totalPages - 1, faAnglesRight)}
      </Box>
      <Box
        component="span"
        sx={{
          py: 1,
          top: 0,
          right: 0,
          position: { md: 'absolute', sm: 'relative' },
          display: 'flex',
          flexWrap: 'wrap',
          justifyContent: 'center',
          alignItems: 'center',        }}
      >
        <Typography variant="body2" component="span" sx={{ mr: 1, color: 'text.secondary' }}>
          Lignes par page
        </Typography>
        <Select
          value={rowsPerPage}
          onChange={handleRowsPerPageChange}
          sx={{ height: '30px', fontSize: 14 }}
          size="small"
        >
          {rowsPerPageOptions.map((option) => (
            <StyledMenuItem key={option} value={option}>
              {option}
            </StyledMenuItem>
          ))}
        </Select>
        {onChangeDense && (
          <FormControlLabel
            label={
              <Typography variant="body2" sx={{ pr: 0.5, color: 'text.secondary' }}>
                Dense
              </Typography>
            }
            sx={{ mr: 1 }}
            labelPlacement="start"
            control={<Switch size="small" checked={dense} onChange={onChangeDense} />}
          />
        )}
      </Box>
    </Box>
  );
}
