import { MoreVert } from '@mui/icons-material'
import {
  IconButton,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
} from '@mui/material'
import type { WrapperOptionsProps } from '../types'
import { useState } from 'react'
import { styles } from '../styles'

const EMPTY_OPTIONS: NonNullable<WrapperOptionsProps['options']> = []

/**
 * Renders a dropdown options menu in the widget wrapper header, triggered by a vertical ellipsis icon button.
 */
export function Options({
  labels,
  options = EMPTY_OPTIONS,
}: WrapperOptionsProps) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)

  const handleOptionAction = (
    e: React.MouseEvent<HTMLElement>,
    option: NonNullable<WrapperOptionsProps['options']>[number],
  ) => {
    e.stopPropagation()
    option.onClick()
    setAnchorEl(null)
  }

  return (
    <>
      <IconButton
        sx={styles.options.trigger}
        size='small'
        aria-label={labels?.title ?? 'Options'}
        aria-controls='options-menu'
        aria-haspopup='true'
        onClick={(e) => {
          e.stopPropagation()
          setAnchorEl(e.currentTarget)
        }}
      >
        <MoreVert />
      </IconButton>
      <Menu
        variant='menu'
        elevation={8}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={() => setAnchorEl(null)}
        MenuListProps={{
          sx: {
            paddingBottom: 0,
          },
        }}
      >
        {options.map((option) => (
          <MenuItem
            key={option.label}
            disabled={option.disabled}
            onClick={(e) => handleOptionAction(e, option)}
          >
            {option.icon && <ListItemIcon>{option.icon}</ListItemIcon>}
            <ListItemText>{option.label}</ListItemText>
          </MenuItem>
        ))}
      </Menu>
    </>
  )
}
