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

/** Button that navigates to the previous step. Disabled on the first step. */
export function WizardPrev(props: WizardPrevProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick", "disabled"]);
  const ctx = useWizardContext();

  const isFirst = () => ctx.currentStep() === 0;
  const isDisabled = () => local.disabled ?? isFirst();

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

  return (
    <button
      type="button"
      disabled={isDisabled() || undefined}
      data-state={isFirst() ? "first" : "default"}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </button>
  );
}
