import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useDatePickerContext } from "./date-picker-context";

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

/** Button that toggles the DatePicker calendar popover open or closed. */
export function DatePickerTrigger(props: DatePickerTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["onClick", "children"]);
  const ctx = useDatePickerContext();

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

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