import { FC, useState, useRef } from 'react';

import ArrowDropDownIcon from '@material-hu/icons/material/ArrowDropDown';
import Box from '@material-hu/mui/Box';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Popover from '@material-hu/mui/Popover';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

export type TabSeeMoreButtonProps = {
  filteredTabs: any;
  currentTab: number | string;
  onChangeTab: (index) => void;
  maxShowIndex: number;
};

export const TabSeeMoreButton: FC<TabSeeMoreButtonProps> = props => {
  const { filteredTabs, currentTab, onChangeTab, maxShowIndex } = props;

  const anchorRef = useRef<HTMLButtonElement | null>(null);

  const { t } = useTranslation();

  const [openPopover, setOpenPopover] = useState(false);

  const renderTabPopover = (tab: any, index) => {
    const { id, title } = tab;

    const handleOnClick = () => {
      onChangeTab(id);
      setOpenPopover(false);
    };

    if (index > maxShowIndex) {
      return (
        <Button
          onClick={handleOnClick}
          key={id}
          fullWidth
          sx={{
            minWidth: '100px',
            display: 'block',
            px: 1,
            borderRadius: '0px',
            borderLeft: theme =>
              id === currentTab
                ? `3px solid ${theme.palette.primary.main}`
                : '0',
          }}
        >
          <Box
            sx={{
              width: '100%',
              display: 'flex',
              justifyContent: 'center',
              color: id === currentTab ? '#433262' : '#6c757d',
            }}
          >
            {title}
          </Box>
        </Button>
      );
    }
    return null;
  };

  return (
    <>
      <ButtonBase
        onClick={() => setOpenPopover(true)}
        ref={anchorRef}
        sx={{ display: 'flex', alignItems: 'center', p: 2 }}
      >
        <Typography
          color="secondary"
          sx={{ fontWeight: 600 }}
        >
          {t('MORE')}
        </Typography>
        <ArrowDropDownIcon
          color="secondary"
          sx={{ ml: 0.5 }}
        />
      </ButtonBase>
      <Popover
        open={openPopover}
        anchorEl={anchorRef.current}
        onClose={() => setOpenPopover(false)}
        anchorOrigin={{
          horizontal: 'left',
          vertical: 'bottom',
        }}
        keepMounted
        sx={{
          '& .MuiPopover-paper': {
            paddingY: '8px',
          },
        }}
      >
        {filteredTabs.map(renderTabPopover)}
      </Popover>
    </>
  );
};

export default TabSeeMoreButton;
