import type { JSX } from "solid-js";
import { onCleanup, onMount, splitProps } from "solid-js";
import { useInternalDropdownMenuContext } from "./dropdown-menu-context";

export interface DropdownMenuItemProps extends JSX.HTMLAttributes<HTMLDivElement> {
  /** The value this item represents. */
  value: string;
  /** Whether this item is disabled. */
  disabled?: boolean | undefined;
  /** Called when the item is activated (click or Enter/Space). */
  onSelect?: (() => void) | undefined;
  children?: JSX.Element;
}

/** A single activatable option within a DropdownMenu. */
export function DropdownMenuItem(props: DropdownMenuItemProps): JSX.Element {
  const [local, rest] = splitProps(props, ["value", "disabled", "onSelect", "children"]);
  const ctx = useInternalDropdownMenuContext();
  const itemProps = () => ctx.navigation.getItemProps(local.value);

  onMount(() => {
    ctx.registerItem(local.value, () => local.onSelect?.());
  });

  onCleanup(() => {
    ctx.unregisterItem(local.value);
  });

  const handleClick: JSX.EventHandler<HTMLDivElement, MouseEvent> = () => {
    if (local.disabled) return;
    local.onSelect?.();
    ctx.close();
  };

  return (
    <div
      aria-disabled={local.disabled || undefined}
      data-disabled={local.disabled || undefined}
      {...itemProps()}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </div>
  );
}
