import React, { forwardRef, useCallback, useEffect, useMemo, useState } from "react";
import { WizardContextProvider } from "./context";
import { Step } from "./Step";
import { Dialog } from "../Dialog";
export const Wizard = /*#__PURE__*/forwardRef((_ref, ref) => {
  let {
    title,
    open,
    onClose,
    disableCloseOnEsc = false,
    children,
    dialogClassName
  } = _ref;
  const childrenCollection = useMemo(() => React.Children.toArray(children), [children]);
  const [activeStep, setActiveStep] = useState(0);
  const [changingStepInProgress, setChangingStepInProgress] = useState(false);
  useEffect(() => {
    if (open) {
      setActiveStep(0);
    }
  }, [open]);
  const goNext = useCallback(() => {
    const index = childrenCollection.findIndex((step, index) => {
      var _stepEl$props;
      const stepEl = step;
      return !(stepEl != null && (_stepEl$props = stepEl.props) != null && _stepEl$props.skip) && index > activeStep;
    });
    setActiveStep(index);
  }, [activeStep, childrenCollection]);
  const goPrevious = useCallback(() => {
    let index = 0;
    for (let i = childrenCollection.length - 1; i >= 0; i--) {
      var _step$props;
      const step = childrenCollection[i];
      if (!(step != null && (_step$props = step.props) != null && _step$props.skip) && i < activeStep) {
        index = i;
        break;
      }
    }
    setActiveStep(index);
  }, [activeStep, childrenCollection]);
  const renderActiveStep = useMemo(() => {
    const element = childrenCollection[activeStep];
    if ((element == null ? void 0 : element.type) === Step) {
      return /*#__PURE__*/React.cloneElement(element, {
        index: activeStep,
        isLast: childrenCollection.length - 1 === activeStep,
        title,
        onNextButtonClick: goNext,
        onPreviousButtonClick: goPrevious,
        onClose,
        changingStepInProgress: changingStepInProgress
      });
    }
    return null;
  }, [activeStep, changingStepInProgress, childrenCollection, goNext, goPrevious, onClose, title]);
  return /*#__PURE__*/React.createElement(WizardContextProvider, {
    value: {
      activeStep,
      setActiveStep,
      goNext,
      goPrevious,
      close: onClose,
      setChangingStepInProgress
    }
  }, /*#__PURE__*/React.createElement(Dialog, {
    ref: ref,
    open: open,
    onClose: onClose,
    disableCloseOnEsc: disableCloseOnEsc,
    className: dialogClassName
  }, renderActiveStep));
});
Wizard.displayName = "Wizard";
//# sourceMappingURL=Wizard.js.map