import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useInternalSelectContext } from "./select-context";

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

/** Button that opens the Select dropdown. */
export function SelectTrigger(props: SelectTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick", "onKeyDown"]);
  const ctx = useInternalSelectContext();

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

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

    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"
      role="combobox"
      id={ctx.triggerId}
      aria-expanded={ctx.isOpen()}
      aria-haspopup="listbox"
      aria-controls={ctx.isOpen() ? ctx.contentId : undefined}
      data-state={ctx.isOpen() ? "open" : "closed"}
      disabled={ctx.disabled()}
      onClick={handleClick}
      onKeyDown={handleKeyDown}
      {...rest}
    >
      {local.children}
    </button>
  );
}
