import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _createForOfIteratorHelper from "@babel/runtime/helpers/createForOfIteratorHelper";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["onSubmit", "onChange", "onError", "formData", "steps", "fillProps", "onPreSubmit"];
import Button from '@material-ui/core/Button';
import Step from '@material-ui/core/Step';
import StepButton from '@material-ui/core/StepButton';
import StepContent from '@material-ui/core/StepContent';
import Stepper from '@material-ui/core/Stepper';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import { mapValues, pick } from 'lodash';
import { forwardRef, useRef, useState } from 'react';
import { FormattedMessage, useIntl } from 'react-intl';
import { StepTitle } from './configToSchemas/types/stepTitle';
import CheckIcon from '@material-ui/icons/Check';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
var useStyles = makeStyles(function (theme) {
  return {
    button: {
      marginRight: theme.spacing(1)
    },
    buttonContainer: {
      '& > *': {
        marginRight: theme.spacing(1),
        marginTop: theme.spacing(1),
        '@media print': {
          display: 'none'
        }
      }
    },
    labelContainer: {
      textAlign: 'start'
    },
    stepIconActive: {
      color: '#0077C7',
      fill: 'currentColor',
      width: '1em',
      height: '1em',
      display: 'inline-block',
      fontSize: '1.5rem',
      transition: 'fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
      flexShrink: '0',
      userSelect: 'none'
    },
    stepIcon: {
      color: 'rgba(0, 0, 0, 0.38)',
      fill: 'currentColor',
      width: '1em',
      height: '1em',
      display: 'inline-block',
      fontSize: '1.5rem',
      transition: 'fill 200ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
      flexShrink: '0',
      userSelect: 'none'
    }
  };
});
export default function withSteps(Form) {
  var WithSteps = /*#__PURE__*/forwardRef(function (_ref, ref) {
    var _ref2;

    var onSubmit = _ref.onSubmit,
        _onChange = _ref.onChange,
        _onError = _ref.onError,
        formData = _ref.formData,
        steps = _ref.steps,
        fillProps = _ref.fillProps,
        onPreSubmit = _ref.onPreSubmit,
        otherProps = _objectWithoutProperties(_ref, _excluded);

    var intl = useIntl();

    var _useState = useState(otherProps.dataIsDraft && otherProps.activeStep ? otherProps.activeStep : 0),
        _useState2 = _slicedToArray(_useState, 2),
        activeStep = _useState2[0],
        setActiveStep = _useState2[1];

    var _useState3 = useState(activeStep),
        _useState4 = _slicedToArray(_useState3, 2),
        maxJump = _useState4[0],
        setMaxJump = _useState4[1];

    var _useState5 = useState(false),
        _useState6 = _slicedToArray(_useState5, 2),
        noValidate = _useState6[0],
        setNoValidate = _useState6[1];

    var _useState7 = useState(false),
        _useState8 = _slicedToArray(_useState7, 2),
        liveValidate = _useState8[0],
        setLiveValidate = _useState8[1];

    var classes = useStyles();
    var formRef = useRef();
    (_ref2 = ref) !== null && _ref2 !== void 0 ? _ref2 : ref = formRef;
    var formWrapperRef = useRef();
    var jumpRef = useRef(null);

    function handleStepChange(args) {
      var _jumpRef$current;

      var nextStep = (_jumpRef$current = jumpRef.current) !== null && _jumpRef$current !== void 0 ? _jumpRef$current : activeStep + 1;

      if (nextStep < steps.length) {
        setMaxJump(function (prev) {
          return Math.max(prev, nextStep);
        });
        setActiveStep(nextStep);
        setTimeout(function () {
          var _steps$nextStep$uiOp, _steps$nextStep$uiOp$, _formWrapperRef$curre, _formWrapperRef$curre2;

          var stepId = 'formula-step-' + ((_steps$nextStep$uiOp = steps[nextStep]['ui:options']) === null || _steps$nextStep$uiOp === void 0 ? void 0 : (_steps$nextStep$uiOp$ = _steps$nextStep$uiOp.element) === null || _steps$nextStep$uiOp$ === void 0 ? void 0 : _steps$nextStep$uiOp$.key);
          var selection = (_formWrapperRef$curre = formWrapperRef.current) === null || _formWrapperRef$curre === void 0 ? void 0 : _formWrapperRef$curre.querySelector('#' + stepId);
          selection.scrollIntoView(true);
          var focusableElements = 'a:not([disabled]), button:not([disabled]), input:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
          var allFocusableElements = (_formWrapperRef$curre2 = formWrapperRef.current) === null || _formWrapperRef$curre2 === void 0 ? void 0 : _formWrapperRef$curre2.querySelectorAll(focusableElements);
          var focusableFormElements = Array.prototype.slice.call(allFocusableElements).filter(function (element) {
            return !element.id.startsWith('formula-step');
          });
          focusableFormElements[0].focus();
        }, 0); // Prevent submit

        return false;
      } // Submit


      return onPreSubmit ? onPreSubmit(args) : true;
    }

    var handleSubmit = function handleSubmit() {
      setNoValidate(false);
    };

    var isLastStep = activeStep === steps.length - 1;
    var elements = otherProps.uiSchema['ui:order'];
    var currentStepElements = [];
    var beforeMaxJumpElements = [];
    var current = -1;

    var _iterator = _createForOfIteratorHelper(elements),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _otherProps$uiSchema$;

        var element = _step.value;
        var uiField = (_otherProps$uiSchema$ = otherProps.uiSchema[element]) === null || _otherProps$uiSchema$ === void 0 ? void 0 : _otherProps$uiSchema$['ui:field'];

        if (uiField === StepTitle) {
          current++;

          if (current > maxJump) {
            break;
          } else {
            continue;
          }
        }

        if (current === -1 && activeStep === 0 || current === activeStep) {
          currentStepElements.push(element);
        }

        beforeMaxJumpElements.push(element);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    var createHandleJump = function createHandleJump(step) {
      return function handleJump(event) {
        // If backward button pressed
        step < activeStep ? setNoValidate(true) : setNoValidate(false);
        setLiveValidate(false);
        jumpRef.current = step;
        ref.current.submit(event); // Wait for the submit event to trigger.

        setTimeout(function () {
          // If form has validation errors, jump does not happen and we must clean
          // current value.
          jumpRef.current = null;
        });
      };
    };

    var StepIcon = function StepIcon(_ref3) {
      var pageNumber = _ref3.pageNumber,
          active = _ref3.active,
          completed = _ref3.completed;
      return /*#__PURE__*/_jsxs("svg", {
        "aria-label": completed ? intl.formatMessage({
          id: "eQag3L",
          defaultMessage: [{
            "type": 0,
            "value": "Ikoni, sivu "
          }, {
            "type": 1,
            "value": "page"
          }, {
            "type": 0,
            "value": ": täytetty"
          }]
        }, {
          page: pageNumber
        }) : active ? intl.formatMessage({
          id: "00WiO4",
          defaultMessage: [{
            "type": 0,
            "value": "Ikoni, sivu "
          }, {
            "type": 1,
            "value": "page"
          }, {
            "type": 0,
            "value": ": aktiivinen"
          }]
        }, {
          page: pageNumber
        }) : intl.formatMessage({
          id: "BM+uIV",
          defaultMessage: [{
            "type": 0,
            "value": "Ikoni, sivu "
          }, {
            "type": 1,
            "value": "page"
          }, {
            "type": 0,
            "value": ": täyttämätön"
          }]
        }, {
          page: pageNumber
        }),
        className: active ? classes.stepIconActive : classes.stepIcon,
        focusable: false,
        viewBox: "0 0 24 24",
        children: [/*#__PURE__*/_jsx("circle", {
          cx: 12,
          cy: 12,
          r: 12,
          "aria-hidden": true
        }), completed ? /*#__PURE__*/_jsx(CheckIcon, {
          style: {
            color: 'white'
          },
          "aria-hidden": true
        }) : /*#__PURE__*/_jsx("text", {
          className: "MuiStepIcon-text",
          x: 12,
          y: 16,
          textAnchor: "middle",
          "aria-hidden": true,
          children: pageNumber
        })]
      });
    };

    return /*#__PURE__*/_jsxs("div", {
      ref: formWrapperRef,
      children: [/*#__PURE__*/_jsx(Typography, {
        component: "h2",
        variant: "h5",
        gutterBottom: true,
        children: otherProps.schema.title
      }), /*#__PURE__*/_jsx(Stepper, {
        activeStep: activeStep,
        orientation: "vertical",
        nonLinear: true,
        children: steps.map(function (_ref4) {
          var title = _ref4['ui:title'],
              options = _ref4['ui:options'];
          return {
            title: title,
            options: options
          };
        }).map(function (_ref5, index) {
          var _options$element, _steps, _otherProps$schema$re, _otherProps$customMes, _otherProps$customMes2, _steps2, _steps3;

          var title = _ref5.title,
              options = _ref5.options;
          var active = index <= maxJump;
          var current = index === activeStep;
          return /*#__PURE__*/_jsxs(Step, {
            children: [/*#__PURE__*/_jsx(StepButton, {
              id: "formula-step-".concat(options === null || options === void 0 ? void 0 : (_options$element = options.element) === null || _options$element === void 0 ? void 0 : _options$element.key),
              completed: index < activeStep,
              disabled: current || !active,
              active: active,
              onClick: createHandleJump(index),
              className: classes.labelContainer,
              icon: /*#__PURE__*/_jsx(StepIcon, {
                pageNumber: index + 1,
                active: active,
                completed: index < activeStep
              }),
              "aria-expanded": current,
              "aria-disabled": current,
              children: /*#__PURE__*/_jsx(Typography, {
                variant: "subtitle2",
                component: "h3",
                children: title
              })
            }), current && /*#__PURE__*/_jsx(StepContent, {
              children: /*#__PURE__*/_jsx(Form, _objectSpread(_objectSpread({}, otherProps), {}, {
                fillProps: isLastStep ? _objectSpread(_objectSpread({}, fillProps), {}, {
                  actions: /*#__PURE__*/_jsxs(_Fragment, {
                    children: [/*#__PURE__*/_jsx(Button, {
                      onClick: createHandleJump(activeStep - 1),
                      "aria-label": "".concat(intl.formatMessage({
                        id: "DeSNU6",
                        defaultMessage: [{
                          "type": 0,
                          "value": "Takaisin"
                        }]
                      }), ": ").concat((_steps = steps[index - 1]) === null || _steps === void 0 ? void 0 : _steps['ui:title']),
                      children: /*#__PURE__*/_jsx(FormattedMessage, {
                        id: "DeSNU6",
                        defaultMessage: [{
                          "type": 0,
                          "value": "Takaisin"
                        }]
                      })
                    }), fillProps === null || fillProps === void 0 ? void 0 : fillProps.actions]
                  })
                }) : fillProps,
                onSubmit: isLastStep ? onSubmit : undefined,
                onPreSubmit: handleStepChange,
                ref: ref,
                isLastStep: isLastStep,
                formData: formData,
                onChange: function onChange() {
                  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                    args[_key] = arguments[_key];
                  }

                  _onChange === null || _onChange === void 0 ? void 0 : _onChange.apply(void 0, args);
                  setMaxJump(activeStep);
                },
                onError: function onError() {
                  setLiveValidate(true);

                  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                    args[_key2] = arguments[_key2];
                  }

                  _onError === null || _onError === void 0 ? void 0 : _onError.apply(void 0, args);
                },
                liveValidate: liveValidate,
                noValidate: noValidate,
                schema: _objectSpread(_objectSpread({}, otherProps.schema), {}, {
                  properties: pick(otherProps.schema.properties, isLastStep ? beforeMaxJumpElements : currentStepElements),
                  title: undefined,
                  required: (_otherProps$schema$re = otherProps.schema.required) === null || _otherProps$schema$re === void 0 ? void 0 : _otherProps$schema$re.filter(function (key) {
                    return currentStepElements.includes(key);
                  })
                }),
                uiSchema: _objectSpread(_objectSpread({
                  formWithSteps: true
                }, mapValues(otherProps.schema.properties, function (value, key) {
                  return currentStepElements.includes(key) ? otherProps.uiSchema[key] : {
                    'ui:widget': 'hidden'
                  };
                })), mapValues(otherProps.uiSchema, function (value, key) {
                  return elements.includes(key) && !currentStepElements.includes(key) ? {
                    'ui:widget': 'hidden'
                  } : value;
                })),
                children: /*#__PURE__*/_jsxs("div", {
                  className: classes.buttonContainer,
                  children: [isLastStep ? /*#__PURE__*/_jsx(Button, {
                    type: "submit",
                    onClick: handleSubmit,
                    variant: "contained",
                    color: "primary",
                    children: (_otherProps$customMes = (_otherProps$customMes2 = otherProps.customMessages) === null || _otherProps$customMes2 === void 0 ? void 0 : _otherProps$customMes2.submit) !== null && _otherProps$customMes !== void 0 ? _otherProps$customMes : /*#__PURE__*/_jsx(FormattedMessage, {
                      id: "6jFMKd",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Lähetä"
                      }]
                    })
                  }) : /*#__PURE__*/_jsx(Button, {
                    onClick: createHandleJump(activeStep + 1),
                    variant: "contained",
                    color: "primary",
                    "aria-label": "".concat(intl.formatMessage({
                      id: "KwX5/f",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Eteenpäin"
                      }]
                    }), ": ").concat((_steps2 = steps[index + 1]) === null || _steps2 === void 0 ? void 0 : _steps2['ui:title']),
                    children: /*#__PURE__*/_jsx(FormattedMessage, {
                      id: "KwX5/f",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Eteenpäin"
                      }]
                    })
                  }), activeStep !== 0 && /*#__PURE__*/_jsx(Button, {
                    onClick: createHandleJump(activeStep - 1),
                    "aria-label": "".concat(intl.formatMessage({
                      id: "DeSNU6",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Takaisin"
                      }]
                    }), ": ").concat((_steps3 = steps[index - 1]) === null || _steps3 === void 0 ? void 0 : _steps3['ui:title']),
                    children: /*#__PURE__*/_jsx(FormattedMessage, {
                      id: "DeSNU6",
                      defaultMessage: [{
                        "type": 0,
                        "value": "Takaisin"
                      }]
                    })
                  }), otherProps.draftButton, (fillProps === null || fillProps === void 0 ? void 0 : fillProps.actions) && fillProps.actions]
                })
              }))
            })]
          }, title);
        })
      })]
    });
  });
  return /*#__PURE__*/forwardRef(function (props, ref) {
    var _props$uiSchema$uiOr, _props$fillProps;

    var uiOrder = (_props$uiSchema$uiOr = props.uiSchema['ui:order']) !== null && _props$uiSchema$uiOr !== void 0 ? _props$uiSchema$uiOr : [];
    var steps = Object.entries(props.uiSchema).sort(function (_ref6, _ref7) {
      var _ref8 = _slicedToArray(_ref6, 1),
          a = _ref8[0];

      var _ref9 = _slicedToArray(_ref7, 1),
          b = _ref9[0];

      return uiOrder.indexOf(a) - uiOrder.indexOf(b);
    }).map(function (_ref10) {
      var _ref11 = _slicedToArray(_ref10, 2),
          value = _ref11[1];

      return value;
    }).filter(Boolean).filter(function (_ref12) {
      var uiField = _ref12['ui:field'];
      return uiField === StepTitle;
    });

    var steppedProps = _objectSpread(_objectSpread({}, props), {}, {
      // In form step schema & uiSchema is incomplete.
      // This is to access the original/full schema & uiSchema.
      __withStepped_original_props__: props
    });

    return !(props === null || props === void 0 ? void 0 : (_props$fillProps = props.fillProps) === null || _props$fillProps === void 0 ? void 0 : _props$fillProps.disableSteps) && steps.length ? /*#__PURE__*/_jsx(WithSteps, _objectSpread(_objectSpread({
      ref: ref
    }, steppedProps), {}, {
      steps: steps
    })) : /*#__PURE__*/_jsx(Form, _objectSpread({
      ref: ref
    }, steppedProps));
  });
}
//# sourceMappingURL=withSteps.js.map