import { type ChangeEvent, type MouseEvent } from 'react';
import { useTranslation } from 'react-i18next';

import { Button, IconButton, Stack } from '@mui/material';
import { IconChevronLeft, IconChevronRight } from '@tabler/icons-react';
import { times } from 'lodash';

import MenuList from '../../../../../composed-components/MenuList';

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

export const PaginationItem = ({
  page,
  type,
  selected,
  disabled = false,
  items,
  onChange,
  ...item
}: PaginationItemProps) => {
  const { t } = useTranslation('material_hu_only');

  let children = null;

  if (type.includes('ellipsis')) {
    const currentItemIndex = items.findIndex(_item => _item.type === type);
    const previousItem = items[currentItemIndex - 1];
    const nextItem = items[currentItemIndex + 1];
    const previousItemPage = previousItem?.page ?? 0;
    const nextItemPage = nextItem?.page ?? 0;
    const ellipsedPagesCount = nextItemPage - previousItemPage - 1;

    const options = times(ellipsedPagesCount, (index: number) => {
      const itemPage = previousItemPage + index + 1;
      return {
        title: `${itemPage}`,
        onClick: (e?: MouseEvent<HTMLLIElement>) => {
          onChange?.(e as ChangeEvent<unknown>, itemPage);
        },
      };
    });

    children = (
      <MenuList
        options={options}
        minWidth={'72px'}
        customButton={
          <Button
            {...item}
            variant="tertiary"
            disabled
            size="small"
            sx={{
              minWidth: '36px',
            }}
            aria-label={t('hu_inputs.show_more_pages')}
          >
            {'...'}
          </Button>
        }
      />
    );
  }

  if (type === 'page') {
    children = (
      <Button
        {...item}
        variant={selected ? 'secondary' : 'tertiary'}
        size="small"
        disabled={disabled}
        sx={{
          minWidth: '36px',
        }}
      >
        {page}
      </Button>
    );
  }

  if (type === 'previous') {
    children = (
      <IconButton
        {...item}
        aria-label={t('hu_inputs.previous')}
        size="small"
        disabled={disabled}
      >
        <IconChevronLeft />
      </IconButton>
    );
  }

  if (type === 'next') {
    children = (
      <IconButton
        {...item}
        aria-label={t('hu_inputs.next')}
        size="small"
        disabled={disabled}
      >
        <IconChevronRight />
      </IconButton>
    );
  }

  return (
    <Stack
      component="li"
      sx={{ listStyle: 'none' }}
    >
      {children}
    </Stack>
  );
};

export type { PaginationItemProps };

export default PaginationItem;
