import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useDropdownMenuRadioGroupContext } from "./dropdown-menu-context";

export interface DropdownMenuRadioItemProps extends JSX.HTMLAttributes<HTMLDivElement> {
  /** The value this radio item represents. */
  value: string;
  /** Whether this item is disabled. */
  disabled?: boolean | undefined;
  children?: JSX.Element;
}

/** A radio-selectable menu item within a DropdownMenu.RadioGroup. */
export function DropdownMenuRadioItem(props: DropdownMenuRadioItemProps): JSX.Element {
  const [local, rest] = splitProps(props, ["value", "disabled", "children"]);
  const radioCtx = useDropdownMenuRadioGroupContext();

  const isChecked = () => radioCtx.value() === local.value;

  const handleClick: JSX.EventHandler<HTMLDivElement, MouseEvent> = () => {
    if (local.disabled) return;
    radioCtx.onValueChange?.(local.value);
  };

  return (
    <div
      role="menuitemradio"
      aria-checked={isChecked()}
      aria-disabled={local.disabled || undefined}
      data-disabled={local.disabled || undefined}
      data-state={isChecked() ? "checked" : "unchecked"}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </div>
  );
}
