/**
 * ToolbarOverflowMenu - Dropdown menu that renders toolbar items that
 * don't fit in the right region of the toolbar.
 *
 * Each overflow item replicates the same icon, label, onClick, disabled,
 * and active states as its inline counterpart.
 */

import React, { useCallback, useRef, useState } from 'react';
import { FiMoreHorizontal } from 'react-icons/fi';
import { useClickOutside } from '../hooks/useClickOutside';
import { t } from '../utils/translation';

export interface OverflowItem {
  /** Matches the `data-toolbar-id` attribute. */
  id: string;
  /** Icon component (e.g. <FiSettings />) */
  icon: React.ReactNode;
  /** Visible label for the menu item. */
  label: string;
  /** Click handler. */
  onClick: () => void;
  /** Whether the button is disabled. */
  disabled?: boolean;
  /** Whether the toggle is active. */
  active?: boolean;
}

interface ToolbarOverflowMenuProps {
  items: OverflowItem[];
}

const ToolbarOverflowMenu: React.FC<ToolbarOverflowMenuProps> = ({ items }) => {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  useClickOutside(
    isOpen,
    [containerRef],
    useCallback(() => setIsOpen(false), []),
  );

  const handleToggle = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsOpen(prev => !prev);
  };

  const handleItemClick = (item: OverflowItem) => {
    if (item.disabled) return;
    item.onClick();
    setIsOpen(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent, item: OverflowItem) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      handleItemClick(item);
    }
    if (e.key === 'Escape') {
      setIsOpen(false);
      buttonRef.current?.focus();
    }
  };

  if (items.length === 0) return null;

  return (
    <div className="toolbar-overflow" ref={containerRef}>
      <button
        ref={buttonRef}
        type="button"
        className="toolbar-btn toolbar-overflow-trigger"
        onClick={handleToggle}
        aria-haspopup="menu"
        aria-expanded={isOpen}
        aria-label={t('More toolbar actions')}
        title={t('More toolbar actions')}
      >
        <FiMoreHorizontal />
      </button>

      {isOpen && (
        <ul
          className="toolbar-overflow-menu"
          role="menu"
          aria-label={t('Additional toolbar actions')}
        >
          {items.map(item => (
            <li
              key={item.id}
              role="menuitem"
              className={`toolbar-overflow-item${item.active ? ' active' : ''}${item.disabled ? ' disabled' : ''}`}
              onClick={() => handleItemClick(item)}
              onKeyDown={(e) => handleKeyDown(e, item)}
              tabIndex={item.disabled ? -1 : 0}
              aria-disabled={item.disabled}
            >
              <span className="toolbar-overflow-item-icon">{item.icon}</span>
              <span className="toolbar-overflow-item-label">{item.label}</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default ToolbarOverflowMenu;
