import { ReactElement, ReactNode, createContext, useContext } from 'react';

interface WizardFormContextValue {
  currentStep: number;
  steps: Array<ReactElement>;
  hasNextStep: () => boolean;
  hasPreviousStep: () => boolean;
  goToNextStep: () => void;
  goToPreviousStep: () => void;
}

const WizardFormContext = createContext<WizardFormContextValue | undefined>(undefined);

/**
 * Custom hook to access the wizard form context.
 * This hook provides access to the current step, steps, and navigation methods
 * for a wizard form.
 *
 * @throws Will throw an error if used outside of a `WizardFormProvider`.
 *
 * @property {number} currentStep - The index of the current step in the wizard form.
 * @property {Array<ReactElement>} steps - An array of React elements representing the steps of the wizard form.
 *
 * @method hasNextStep
 * @returns {boolean} - Returns true if there is a next step available, otherwise false.
 *
 * @method hasPreviousStep
 * @returns {boolean} - Returns true if there is a previous step available, otherwise false.
 *
 * @method goToNextStep
 * @returns {void} - Advances to the next step in the wizard form.
 *
 * @method goToPreviousStep
 * @returns {void} - Goes back to the previous step in the wizard form.
 *
 *
 * @example
 * const { hasNextStep, goToNextStep } = useWizardFormContext();
 * return (
 *  <Button disabled={!hasNextStep} onClick={goToNextStep}>
 *   Next
 * </Button>
 * );
 */
function useWizardFormContext() {
  const context = useContext(WizardFormContext);
  if (!context) {
    throw new Error('useWizardFormContext must be used within a WizardFormProvider');
  }
  return context;
}

interface WizardFormProviderProps {
  value: WizardFormContextValue;
  children: ReactNode;
}

function Provider({ value, children }: WizardFormProviderProps) {
  return <WizardFormContext.Provider value={value}>{children}</WizardFormContext.Provider>;
}

export { Provider, useWizardFormContext };
