"use client";

import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

export type GroupMenuAction = "edit" | "members" | "rename" | "duplicate" | "delete";

interface MenuItem {
  action: GroupMenuAction;
  label: string;
  icon: string;
  danger?: boolean;
  /** Renders a separator above this item. */
  separated?: boolean;
}

/**
 * The ⋯ menu on a group card and in the editor hero (PRD §8.5's "⋯ menu with
 * Edit rules, Rename, Duplicate, Manage members, Delete").
 *
 * `.bz-menu` is `position: fixed` in the design's stylesheet, so this portals
 * to the body and positions from the trigger's viewport rect. Rendered inside
 * the card instead, it would be clipped by the card's own `overflow` and by the
 * grid's stacking context.
 *
 * Which items appear depends on where it was opened from and what the group is:
 *
 *   - **Edit rules / Manage members** are omitted inside the editor — you are
 *     already there, and the hero has its own Manage members button.
 *   - **Manage members** is omitted for the default group entirely. Its
 *     membership is "everyone not in another group", including rows that point
 *     at nothing, so there is no list to edit; the API refuses it too.
 *   - **Delete** is omitted for the default group (PRD §8.5), which can be
 *     renamed but never deleted.
 */
export default function GroupMenu({
  anchor,
  group,
  context,
  onSelect,
  onClose,
}: {
  anchor: HTMLElement;
  group: { isDefault: boolean };
  context: "card" | "editor";
  onSelect: (action: GroupMenuAction) => void;
  onClose: () => void;
}) {
  const menuRef = useRef<HTMLDivElement>(null);
  const [position, setPosition] = useState<{ top: number; left: number } | null>(null);

  const items: MenuItem[] = [];
  if (context === "card") {
    items.push({ action: "edit", label: "Edit policy", icon: "bi-sliders" });
    if (!group.isDefault) {
      items.push({ action: "members", label: "Manage members", icon: "bi-person-gear" });
    }
  }
  items.push({ action: "rename", label: "Rename", icon: "bi-pencil" });
  items.push({ action: "duplicate", label: "Duplicate", icon: "bi-copy" });
  if (!group.isDefault) {
    items.push({
      action: "delete",
      label: "Delete group",
      icon: "bi-trash3",
      danger: true,
      separated: true,
    });
  }

  // Measured before paint: positioning from an effect would show the menu at
  // 0,0 for a frame first.
  useLayoutEffect(() => {
    const menu = menuRef.current;
    if (!menu) return;
    const trigger = anchor.getBoundingClientRect();
    const box = menu.getBoundingClientRect();
    const gap = 6;

    // Right-aligned to the trigger, flipped to stay on screen.
    let left = trigger.right - box.width;
    if (left < 8) left = 8;
    if (left + box.width > window.innerWidth - 8) left = window.innerWidth - box.width - 8;

    // Below the trigger, or above it when there is no room underneath.
    let top = trigger.bottom + gap;
    if (top + box.height > window.innerHeight - 8) {
      const above = trigger.top - box.height - gap;
      top = above >= 8 ? above : Math.max(8, window.innerHeight - box.height - 8);
    }

    setPosition({ top, left });
    menu.querySelector<HTMLButtonElement>("button")?.focus();
  }, [anchor]);

  useEffect(() => {
    const onDocumentDown = (event: MouseEvent) => {
      const target = event.target as Node;
      // The trigger itself is excluded so its own click can toggle the menu
      // shut, rather than this closing it and the click reopening it.
      if (menuRef.current?.contains(target) || anchor.contains(target)) return;
      onClose();
    };
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.stopPropagation();
        onClose();
        anchor.focus();
        return;
      }
      if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
      const buttons = Array.from(
        menuRef.current?.querySelectorAll<HTMLButtonElement>("button") ?? []
      );
      if (buttons.length === 0) return;
      event.preventDefault();
      const current = buttons.indexOf(document.activeElement as HTMLButtonElement);
      const next =
        event.key === "ArrowDown"
          ? (current + 1 + buttons.length) % buttons.length
          : (current - 1 + buttons.length) % buttons.length;
      buttons[next === -1 ? 0 : next].focus();
    };

    document.addEventListener("mousedown", onDocumentDown);
    document.addEventListener("keydown", onKeyDown, true);
    // A menu positioned against a viewport rect is wrong the moment the page
    // moves, and there is no sensible "follow" behaviour for a transient popover.
    window.addEventListener("scroll", onClose, true);
    window.addEventListener("resize", onClose);
    return () => {
      document.removeEventListener("mousedown", onDocumentDown);
      document.removeEventListener("keydown", onKeyDown, true);
      window.removeEventListener("scroll", onClose, true);
      window.removeEventListener("resize", onClose);
    };
  }, [anchor, onClose]);

  if (typeof document === "undefined") return null;

  return createPortal(
    <div
      ref={menuRef}
      className="bz-ui bz-menu"
      role="menu"
      style={{
        top: position?.top ?? 0,
        left: position?.left ?? 0,
        // Hidden until measured, so it never flashes in the wrong place.
        visibility: position ? "visible" : "hidden",
      }}
    >
      {items.map((item) => (
        <div key={item.action}>
          {item.separated && <hr />}
          <button
            type="button"
            role="menuitem"
            className={item.danger ? "is-danger" : undefined}
            onClick={() => {
              onSelect(item.action);
              onClose();
            }}
          >
            <i className={`bi ${item.icon}`} aria-hidden="true" />
            <span>{item.label}</span>
          </button>
        </div>
      ))}
    </div>,
    document.body
  );
}
