import { type ChangeEvent, type FC } from 'react';

import { Paper } from '@mui/material';
import usePagination from '@mui/material/usePagination';
import { isNumber } from 'lodash';

import PaginationChanger from './components/PaginationChanger';
import PaginationNav from './components/PaginationNav';
import { type PaginationProps } from './types';

export const Pagination: FC<PaginationProps> = ({
  loading = false,
  disabled = false,
  type = 'changer',
  totalPages,
  page,
  onChangePage = () => null,
  limit,
  limitOptions,
  onChangeLimit = () => null,
  sx = {},
}) => {
  const handleChange = (_: ChangeEvent<unknown>, newPage: number) => {
    if (isNumber(newPage)) {
      onChangePage(newPage);
    }
  };

  const { items } = usePagination({
    count: totalPages,
    disabled,
    page,
    onChange: handleChange,
  });

  return (
    <Paper
      variant="outlined"
      sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        p: 1.5,
        gap: 3,
        borderColor: theme => theme.palette.new.border.neutral.default,
        ...sx,
      }}
    >
      <PaginationNav
        loading={loading}
        items={items}
        page={page}
        onChange={handleChange}
      />
      {type === 'changer' && (
        <PaginationChanger
          limit={limit}
          limitOptions={limitOptions}
          onChange={onChangeLimit}
          loading={loading}
          disabled={disabled}
        />
      )}
    </Paper>
  );
};

export type { PaginationProps };

export default Pagination;
