import * as React from "react";
import { FormElementProps, FormElementRegistration } from "@vertigis/workflow";
import Button from '@vertigis/web/ui/Button';
import Menu from '@vertigis/web/ui/Menu';
import MenuItem from '@vertigis/web/ui/MenuItem';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';

/**
 * The generic type argument provided to `FormElementProps<T>` controls the type
 * of `props.value` and `props.setValue(value)`. If your element doesn't need a
 * `value`, you can omit the type argument.
 *
 * You can also declare additional public properties of your element by adding
 * properties to this interface. The properties will be managed by the Workflow
 * runtime, and passed in as `props`. You can update the properties by using
 * `props.setProperty(key, value)`.
 */

interface MenuItem {
  title: string;
  items: string[];
  showIcon?: boolean;  // Changed from startIcon to showIcon for clarity
}

interface MenueBarProps extends FormElementProps<string> {
    structure: MenuItem[];
    selectedItem?: string;
}

/**
 * A Workflow element built using React.
 * @displayName MenueBar
 * @description Menue Bar
 * @param props The props that will be provided by the Workflow runtime.
 */
function MenueBar(props: MenueBarProps): React.ReactElement {
    const { structure, raiseEvent, setProperty } = props;
    
    // State to track which category menu is open
    const [anchorElMap, setAnchorElMap] = React.useState<{[key: string]: HTMLElement | null}>({});
    
    const handleClick = (event: React.MouseEvent<HTMLElement>, category: string) => {
      // Update anchor element for the specific category
      setAnchorElMap(prev => ({
        ...prev,
        [category]: event.currentTarget
      }));
    };
    
    const handleClose = (category: string) => {
      // Close the specific category menu
      setAnchorElMap(prev => ({
        ...prev,
        [category]: null
      }));
    };
    
    const handleMenuItemClick = (category: string, item: string) => {
      // Handle menu item click - set the selected value
      handleClose(category);
      setProperty("selectedItem" as any, {category, item}); 
      raiseEvent("clicked" as any, {category, item});
    };
  
    return (
      <div style={{ display: 'flex', gap: '8px' }}>
        {structure.map((group) => (
          <div key={group.title}>
            <Button
              aria-controls={anchorElMap[group.title] ? `menu-${group.title}` : undefined}
              aria-haspopup="true"
              aria-expanded={anchorElMap[group.title] ? 'true' : undefined}
              variant="contained"
              disableElevation
              onClick={(e) => handleClick(e, group.title)}
              endIcon={group.showIcon ? <KeyboardArrowDownIcon /> : null}
            >
              {group.title}
            </Button>
            <Menu
              id={`menu-${group.title}`}
              anchorEl={anchorElMap[group.title]}
              open={Boolean(anchorElMap[group.title])}
              onClose={() => handleClose(group.title)}
              MenuListProps={{
                'aria-labelledby': group.title,
              }}
            >
              {group.items.map((item) => (
                <MenuItem 
                  key={item}
                  onClick={() => handleMenuItemClick(group.title, item)} 
                  disableRipple
                >
                  {item}
                </MenuItem>
              ))}
            </Menu>
          </div>
        ))}
      </div>
    );
}

const MenueBarElementRegistration: FormElementRegistration<MenueBarProps> = {
    component: MenueBar,
    getInitialProperties: () => ({ 
        structure: [
            {title: "Option 1", items: ['Button A', 'Button B']}, 
            {title: "Item B", items: ['Button C'], showIcon: true}, 
            {title: "Option 2", items: ['Button D', 'Button E']}, 
        ],
        selectedItem: undefined 
    }),
    id: "MenueBar",
};

export default MenueBarElementRegistration;
