import { type FC, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { Button, Typography } from '@mui/material';
import { IconChevronDown } from '@tabler/icons-react';

import Menu from '../../../../Menu';
import MenuItem from '../../../../Menu/components/MenuItem';
import Skeleton from '../../../../Skeleton';

import { type PaginationChangerProps } from './types';

export const PaginationChanger: FC<PaginationChangerProps> = ({
  loading = false,
  limit = 10,
  limitOptions = [10, 20, 30],
  onChange = () => null,
  disabled = false,
}) => {
  const [anchorEl, setAnchorEl] = useState(null);

  const { t } = useTranslation('material_hu_only');

  const open = Boolean(anchorEl);

  const handleOpen = (event: any) => setAnchorEl(event.currentTarget);
  const handleClose = () => setAnchorEl(null);

  const handleSelect = (option: number) => {
    onChange(option);
    handleClose();
  };

  return (
    <>
      {loading && (
        <Skeleton
          width={115}
          height={36}
        />
      )}
      {!loading && (
        <>
          <Button
            variant="secondary"
            size="small"
            onClick={handleOpen}
            disabled={disabled}
            endIcon={<IconChevronDown size={16} />}
          >
            {t('hu_inputs.limit_label', { limit })}
          </Button>
          <Menu
            open={open}
            anchorEl={anchorEl}
            onClose={handleClose}
            fixedDimensions={false}
          >
            {limitOptions.map(option => (
              <MenuItem
                key={option}
                selected={option === limit}
                onClick={() => handleSelect(option)}
              >
                <Typography
                  variant="inherit"
                  noWrap
                >
                  {t('hu_inputs.limit_label', { limit: option })}
                </Typography>
              </MenuItem>
            ))}
          </Menu>
        </>
      )}
    </>
  );
};

export type { PaginationChangerProps };

export default PaginationChanger;
