import { useRef, useState } from 'react';

import Menu from '@design-system/Menu';
import MenuItem from '@design-system/Menu/components/MenuItem';

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

const TableMenuItem = ({
  label,
  options,
  onClick,
  onMouseEnter,
  onClose,
  onSubmenuOpen,
  onSubmenuClose,
  ...item
}: TableMenuItemProps) => {
  const [open, setOpen] = useState(false);

  const anchorRef = useRef<HTMLLIElement | null>(null);
  const menuRef = useRef<HTMLDivElement | null>(null);

  const handleOpen = () => {
    onSubmenuOpen?.(handleClose);
    setOpen(true);
  };

  const handleClose = () => {
    onSubmenuClose?.(handleClose);
    setOpen(false);
  };

  const handleOptionClick = (event: React.MouseEvent<HTMLLIElement>) => {
    event.stopPropagation();
    event.preventDefault();
    onClose(event);
    onClick?.(event);
  };

  const handleOptionMouseEnter = (event: React.MouseEvent<HTMLLIElement>) => {
    const target = event.currentTarget;
    const liElement = target.closest('li') as HTMLLIElement;

    anchorRef.current = liElement ?? (target as HTMLLIElement);

    handleOpen();
    onMouseEnter?.(event);
  };

  return (
    <>
      <MenuItem
        {...item}
        onClick={handleOptionClick}
        onMouseEnter={handleOptionMouseEnter}
      >
        {label}
      </MenuItem>
      {options && (
        <div ref={menuRef}>
          <Menu
            open={open}
            anchorEl={anchorRef.current}
            onClose={handleClose}
            position="top-right"
            sx={{ minWidth: '200px' }}
          >
            {options.map(option => (
              <TableMenuItem
                key={option.label}
                onClose={onClose}
                {...option}
              />
            ))}
          </Menu>
        </div>
      )}
    </>
  );
};

export default TableMenuItem;
