import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useRadioGroupContext } from "./radio-group-context";

export interface RadioGroupItemProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  value: string;
  disabled?: boolean;
  children?: JSX.Element;
}

/**
 * A single radio option within a RadioGroup.
 * Arrow keys navigate between items; clicking selects.
 */
export function RadioGroupItem(props: RadioGroupItemProps): JSX.Element {
  const [local, rest] = splitProps(props, ["value", "disabled", "children"]);
  const ctx = useRadioGroupContext();

  const isChecked = () => ctx.value() === local.value;
  const isDisabled = () => local.disabled || ctx.disabled();

  return (
    <button
      type="button"
      role="radio"
      aria-checked={isChecked() ? "true" : "false"}
      data-state={isChecked() ? "checked" : "unchecked"}
      disabled={isDisabled()}
      tabIndex={isChecked() ? 0 : -1}
      {...rest}
      onClick={(e) => {
        if (typeof rest.onClick === "function") rest.onClick(e);
        if (!isDisabled()) ctx.onValueChange(local.value);
      }}
      onKeyDown={(e) => {
        if (typeof rest.onKeyDown === "function") rest.onKeyDown(e);
        if (isDisabled()) return;

        const group = (e.currentTarget as HTMLButtonElement).closest("[role='radiogroup']");
        if (!group) return;

        const items = Array.from(
          group.querySelectorAll<HTMLButtonElement>("[role='radio']:not([disabled])"),
        );
        const index = items.indexOf(e.currentTarget as HTMLButtonElement);

        if (e.key === "ArrowDown" || e.key === "ArrowRight") {
          e.preventDefault();
          const next = items[(index + 1) % items.length];
          next?.focus();
        } else if (e.key === "ArrowUp" || e.key === "ArrowLeft") {
          e.preventDefault();
          const prev = items[(index - 1 + items.length) % items.length];
          prev?.focus();
        }
      }}
    >
      {local.children}
    </button>
  );
}
