import React, { useState } from 'react';
import { MenuProps } from './types';

type MenuContextType = {
  optionsAnchorEl: (EventTarget & HTMLButtonElement) | null;
  toggleMenu: (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
  setOptionsAnchorEl: React.Dispatch<React.SetStateAction<(EventTarget & HTMLButtonElement) | null>>;
};

export const MenuContext = React.createContext<MenuContextType>({
  optionsAnchorEl: null,
  toggleMenu: () => {},
  setOptionsAnchorEl: () => {},
});

export const useInitMenuContext = (setIsOpen: MenuProps['setIsOpen'] = () => {}): MenuContextType => {
  const [optionsAnchorEl, setOptionsAnchorEl] = useState<(EventTarget & HTMLButtonElement) | null>(null);

  const toggleMenu = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.stopPropagation();
    if (optionsAnchorEl) {
      setIsOpen(false);
      return setOptionsAnchorEl(null);
    }
    setIsOpen(true);
    return setOptionsAnchorEl(e.currentTarget);
  };

  return { optionsAnchorEl, toggleMenu, setOptionsAnchorEl };
};
