import React from 'react';
import { useOutsideClick } from '../../hooks';
import { ButtonVariant } from '../../interfaces';
import Button from '../Button';
import SelectMenu from '../SelectMenu';
import { SelectOptionType } from '../SelectMenu/interfaces';
import { Wrapper } from './styles';

export type ButtonDropdownMenuProps = {
  buttonIcon: React.ReactNode;
  buttonVariant: ButtonVariant;
  buttonText: string;
  handleOptionClick: (selectOption: SelectOptionType) => void;
  options: SelectOptionType[];
  selectMenuWidth?: string;
};

const ButtonDropdownMenu: React.FC<ButtonDropdownMenuProps> = ({
  buttonIcon,
  buttonVariant,
  buttonText,
  handleOptionClick,
  options,
  selectMenuWidth,
}) => {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const wrapperRef = React.useRef<HTMLDivElement>(null);
  useOutsideClick(wrapperRef, () => setMenuOpen(false));
  const onOptionClick = (opt: SelectOptionType) => {
    setMenuOpen(false);
    handleOptionClick(opt);
  };

  const onClickHandler = () => {
    setMenuOpen(!menuOpen);
  };

  return (
    <Wrapper ref={wrapperRef}>
      <Button
        togglesExpand
        icon={buttonIcon}
        iconPosition="left"
        variant={buttonVariant}
        title={buttonText}
        padding="8"
        onClick={onClickHandler}
        toggleArrowPointsUp={menuOpen}
      />
      {menuOpen && (
        <SelectMenu
          menuPosition="fixed"
          wrapperElementRef={wrapperRef}
          onOptionClick={onOptionClick}
          options={options}
          selectMenuWidth={selectMenuWidth}
        />
      )}
    </Wrapper>
  );
};

export default ButtonDropdownMenu;
