import { memo, useCallback, useMemo, useState } from 'react';
import type { MouseEventHandler } from 'react';
import clsx from 'clsx';

import MuiButtonGroup from '@mui/material/ButtonGroup';

import { ASSETS_URL } from '../../consts/common';
import { Button } from '../button';
import { CustomIcon } from '../custom-icon';
import { DropdownMenu } from '../dropdown-menu';

import type { ButtonsWithMenuProps } from './types';
import createClasses from './styles';

const anchorElTopAddition = 9;

const ButtonsWithMenu = (props: ButtonsWithMenuProps) => {
  const {
    size = 'medium',
    countOfVisible = 3,
    listItems,
    clickHandler,
    handleDelete,
    onSortEnd,
    buttonGroupProps
  } = props;

  const classes = createClasses();

  const [anchorEl, setAnchorEl] = useState<(EventTarget & HTMLButtonElement) | null>(null);

  const hasSelectedItems = useMemo(() => {
    return !!listItems.slice(countOfVisible).find(item => item.selected === true);
  }, [countOfVisible, listItems]);

  const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = useCallback(event => {
    setAnchorEl(event?.currentTarget);
  }, []);

  const handleClose = useCallback(() => {
    setAnchorEl(null);
  }, []);

  return (
    <MuiButtonGroup role="radiogroup" size={size} {...buttonGroupProps}>
      {listItems.slice(0, countOfVisible).map(item => {
        const { name, selected, disabled } = item;
        return (
          <Button
            role="radio"
            key={name}
            onClick={clickHandler(name)}
            className={clsx(classes.button, selected && classes.selectedButton)}
            disabled={disabled}
            disableElevation
            variant="contained"
            color="secondary"
            size={size}
          >
            {name}
          </Button>
        );
      })}
      <Button
        data-testid="dotsButton"
        className={clsx(
          classes.button,
          // highlight dropdown's button
          hasSelectedItems && classes.selectedButton
        )}
        disabled={listItems?.length < 1}
        onClick={handleOpenMenu}
        variant="contained"
        color="secondary"
        size={size}
      >
        <CustomIcon
          color="inherit"
          size="small"
          src={`${ASSETS_URL}/icons/icon_3dots.svg`}
          className={classes.dotsIcon}
        />
      </Button>
      {anchorEl && (
        <DropdownMenu
          disablePortal={false}
          showSelectedIcon={false}
          arrowSide="topRight"
          open={!!anchorEl}
          onClose={handleClose}
          anchorEl={anchorEl}
          anchorElTopAddition={anchorElTopAddition}
          listItems={listItems}
          handleClick={clickHandler}
          sortable
          onSortEnd={onSortEnd}
          deletable
          handleDelete={handleDelete}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'right'
          }}
          classes={{
            menuRoot: classes.menuRoot
          }}
        />
      )}
    </MuiButtonGroup>
  );
};

const m = memo(ButtonsWithMenu);
export { m as ButtonsWithMenu };
