var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { yupResolver } from "@hookform/resolvers/yup";
import React, { Children, useEffect, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import styled from "styled-components";
import { FieldErrMessage } from "../../TextField";
import { DevTool } from "@hookform/devtools";
var Parent = styled.div(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n  width: 100%;\n  z-index: 10;\n  display: flex;\n  position: relative;\n  > form {\n    width: inherit;\n  }\n"], ["\n  width: 100%;\n  z-index: 10;\n  display: flex;\n  position: relative;\n  > form {\n    width: inherit;\n  }\n"])));
var FormDiv = styled.div(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n  width: 100%;\n  position: relative;\n  display: flex;\n"], ["\n  width: 100%;\n  position: relative;\n  display: flex;\n"])));
var ButtonsHolder = styled.div(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n  display: flex;\n"], ["\n  display: flex;\n"])));
var FormTemplate = React.forwardRef(function (_a, ref) {
    var actionButton = _a.actionButton, cancelButton = _a.cancelButton, defaultValues = _a.defaultValues, close = _a.close, children = _a.children, validation = _a.validation, actionCreator = _a.actionCreator, renderSubmittingContainer = _a.renderSubmittingContainer, sideTab = _a.sideTab, callback = _a.callback, customWidth = _a.customWidth, customHeight = _a.customHeight, customMargin = _a.customMargin, _b = _a.flexDirection, flexDirection = _b === void 0 ? "column" : _b, formPadding = _a.formPadding, parentJustifyContent = _a.parentJustifyContent, buttonsJustifyContent = _a.buttonsJustifyContent, buttonsMargin = _a.buttonsMargin, customSubmittingContainerTimeout = _a.customSubmittingContainerTimeout, pageSubmitError = _a.pageSubmitError, dispatch = _a.dispatch, customButtons = _a.customButtons, devtools = _a.devtools;
    var methods = useForm({
        resolver: yupResolver(validation),
        defaultValues: defaultValues
    });
    // Resetting the form when we move between pages.
    useEffect(function () {
        methods.reset(defaultValues);
    }, [window.location.href]);
    var _c = __read(useState(false), 2), submitting = _c[0], setSubmitting = _c[1];
    var _d = __read(useState(false), 2), submitted = _d[0], setSubmitted = _d[1];
    var _e = __read(useState({ message: null }), 2), submitError = _e[0], setSubmitError = _e[1];
    var onSubmit = function (data) { return __awaiter(void 0, void 0, void 0, function () {
        var res;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    setSubmitting(true);
                    return [4 /*yield*/, dispatch(actionCreator(data))];
                case 1:
                    res = _a.sent();
                    // Still the same time out but the error now dissapears
                    // in the same amount of time.
                    if ((res === null || res === void 0 ? void 0 : res.message) === "success" ||
                        (res === null || res === void 0 ? void 0 : res.meta.requestStatus) === "fulfilled") {
                        setSubmitting(false);
                        methods.reset(data);
                    }
                    else {
                        setSubmitError({ message: (res === null || res === void 0 ? void 0 : res.message) || "Error" });
                        setSubmitting(false);
                        setSubmitted(true);
                    }
                    if (callback)
                        callback(Object.values(data));
                    if (!!renderSubmittingContainer) {
                        return [2 /*return*/, setTimeout(function () {
                                // Getting the submitting container
                                var submitContainer = document.getElementById("submitContainer");
                                // If it isn't null, we add fadeOut animation, and on animation
                                // end we setSubmitting to false.
                                if (submitContainer !== null) {
                                    submitContainer.classList.add("animate__fadeOut");
                                    submitContainer.addEventListener("animationend", function () {
                                        setSubmitting(false);
                                        setSubmitted(false);
                                        submitContainer.classList.remove("animate__fadeOut");
                                        // setSubmitError({ message: null });
                                    });
                                }
                                // Then close callback is called
                                return close === null || close === void 0 ? void 0 : close({
                                    res: res,
                                    reset: methods.reset
                                });
                            }, customSubmittingContainerTimeout !== undefined
                                ? customSubmittingContainerTimeout
                                : res.message === "success"
                                    ? 1500
                                    : 2500)];
                    }
                    close === null || close === void 0 ? void 0 : close({
                        res: res,
                        reset: methods.reset
                    });
                    return [2 /*return*/];
            }
        });
    }); };
    // This is the main helper function that renders of children props. If custom
    // grouping or styling is being applied, we check if a div is being passed,
    // and render out it's formField children, then pass custom formController props.
    function renderChild(Child) {
        if ((Child === null || Child === void 0 ? void 0 : Child.type) === "div" && typeof (Child === null || Child === void 0 ? void 0 : Child.props.children) !== "string") {
            return (_jsx("div", __assign({ style: Child.props.style }, { children: Child.props.children.map(function (subChild, i) {
                    return subChild.type !== "div" ? (_jsx("div", __assign({ style: { width: "100%" } }, { children: React.cloneElement(subChild, { validation: validation }) }), i)) : (_jsx("div", __assign({ style: { width: "100%" } }, { children: React.cloneElement(subChild, { validation: validation }) }), i));
                }) })));
        }
        else {
            return React.cloneElement(Child, { validation: validation });
        }
    }
    return (_jsxs(Parent, __assign({ style: { justifyContent: parentJustifyContent || "center" } }, { children: [!!sideTab && sideTab, renderSubmittingContainer === null || renderSubmittingContainer === void 0 ? void 0 : renderSubmittingContainer({ submitting: submitting, submitted: submitted, submitError: submitError }), _jsxs(FormProvider, __assign({}, methods, { children: [_jsxs("form", __assign({ onSubmit: methods.handleSubmit(onSubmit), style: {
                            width: customWidth ? customWidth : "inherit",
                            height: customHeight ? customHeight : "inherit",
                            margin: customMargin ? customMargin : "0px",
                            padding: formPadding
                        }, ref: ref }, { children: [_jsx(FormDiv, __assign({ style: { flexDirection: flexDirection } }, { children: Children.map(children, function (Child) { return Child !== null && renderChild(Child); }) })), pageSubmitError && (_jsx(FieldErrMessage, { children: submitError.message })), customButtons ? (actionButton({
                                submitting: submitting,
                                isDirty: methods.formState.isDirty,
                                reset: methods.reset
                            })) : (_jsxs(ButtonsHolder, __assign({ style: {
                                    justifyContent: buttonsJustifyContent || "flex-end",
                                    margin: buttonsMargin || "20px 0px 10px 0px"
                                } }, { children: [cancelButton && (_jsx("div", __assign({ style: { marginRight: "12px" } }, { children: cancelButton }))), actionButton({
                                        submitting: submitting,
                                        isDirty: methods.formState.isDirty,
                                        reset: methods.reset
                                    })] })))] })), devtools && _jsx(DevTool, { control: methods.control })] }))] })));
});
export var Form = FormTemplate;
var templateObject_1, templateObject_2, templateObject_3;
//# sourceMappingURL=index.js.map