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

/** Button that marks the current step complete and advances to the next step. */
export function WizardNext(props: WizardNextProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick", "disabled"]);
  const ctx = useWizardContext();

  const isLast = () => ctx.currentStep() === ctx.totalSteps() - 1;
  const isDisabled = () => local.disabled ?? false;

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

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