import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useWizardContext, useWizardStepContext } from "./wizard-context";
import type { WizardStepTriggerProps } from "./wizard.props";

/** Clickable step indicator. Navigates to the step when clicked (if reachable). */
export function WizardStepTrigger(props: WizardStepTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick", "disabled"]);
  const ctx = useWizardContext();
  const step = useWizardStepContext();

  const isReachable = () => ctx.isStepReachable(step.index);
  const isDisabled = () => (local.disabled ?? step.isDisabled()) || !isReachable();

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

  return (
    <button
      type="button"
      role="tab"
      id={step.triggerId}
      aria-selected={step.isActive() ? "true" : "false"}
      aria-controls={step.contentId}
      data-state={step.isActive() ? "active" : step.isCompleted() ? "completed" : "upcoming"}
      tabIndex={step.isActive() ? 0 : -1}
      disabled={isDisabled() || undefined}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </button>
  );
}
