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

export interface DropdownMenuTriggerProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  children?: JSX.Element;
}

/** Button that opens the DropdownMenu. */
export function DropdownMenuTrigger(props: DropdownMenuTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick", "onKeyDown"]);
  const ctx = useInternalDropdownMenuContext();

  const handleClick: JSX.EventHandler<HTMLButtonElement, MouseEvent> = (e) => {
    if (typeof local.onClick === "function") local.onClick(e);
    ctx.toggle();
  };

  const handleKeyDown: JSX.EventHandler<HTMLButtonElement, KeyboardEvent> = (e) => {
    if (typeof local.onKeyDown === "function") local.onKeyDown(e);

    if (e.key === "ArrowDown") {
      e.preventDefault();
      ctx.open();
      ctx.navigation.highlightFirst();
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      ctx.open();
      ctx.navigation.highlightLast();
    }
  };

  return (
    <button
      ref={(el) => ctx.setTriggerRef(el)}
      type="button"
      id={ctx.triggerId}
      aria-expanded={ctx.isOpen()}
      aria-haspopup="menu"
      aria-controls={ctx.isOpen() ? ctx.contentId : undefined}
      data-state={ctx.isOpen() ? "open" : "closed"}
      onClick={handleClick}
      onKeyDown={handleKeyDown}
      {...rest}
    >
      {local.children}
    </button>
  );
}
