;(function ($) {
    function getDataForm(id) {
        var dataForm = {},
            form = document.forms[id];

        if (document.forms[id] !== undefined) {
            Array.prototype.forEach.call(form.elements, function (elem, index) {
                if (!elem.disabled) {
                    if (elem.type === "checkbox" || elem.type === "radio") {
                        dataForm[elem.name] = elem.checked.toString();
                    } else {
                        dataForm[elem.name] = elem.value;
                    }
                }
            });
        }

        return dataForm;
    }

    function loadTemplate(elem, idTemplate, data, visible, callback, append, prepend) {
        var jElem = $(elem);

        if (typeof elem === "string" && elem.match(/\#/)) {
            elem = elem.replace(/\#/, "");
            jElem = $(document.getElementById(elem));
        }

        var html = _.template(document.getElementById(idTemplate).innerHTML),
            hiddenClass = window.bs_data.hidden_class;

        if (visible) {
            jElem.removeClass(hiddenClass);
        }

        if (append !== undefined) {
            if (prepend !== undefined) {
                jElem.prepend(html(data));
            } else {
                jElem.append(html(data));
            }
        } else {
            jElem.html(html(data));
        }

        if (callback !== undefined) {
            callback();
        }
    }

    function loadTemplateInsert(elem, idTemplate, data, append, prepend, callback) {
        var jElem = $(elem),
            html = _.template(document.getElementById(idTemplate).innerHTML);

        if (append !== undefined) {
            if (prepend !== undefined) {
                jElem.prepend(html(data));
            } else {
                jElem.append(html(data));
            }
        } else {
            jElem.html(html(data));
        }

        if (callback !== undefined) {
            callback();
        }
    }

    function scrollTo(element, offset) {
        const elementPosition = element.getBoundingClientRect().top + window.pageYOffset;
        const offsetPosition = elementPosition - offset;
        window.scrollTo({
            top: offsetPosition,
            behavior: 'smooth'
        });
    }

    function action(wrapper) {
        const submissionForm = document.getElementById('bp-submission-form');
        const loader = submissionForm.querySelector('.bs-loader');
        const progressElements = document.querySelectorAll('.progress-bar-elem');
        if (!!submissionForm) {
            submissionForm.addEventListener('submit', async function (event) {
                event.preventDefault();

                let data = getDataForm(event.target.id),
                    bidspiritUser = bidspiritApi.getBidspiritUser(),
                    errorList = [];

                loader.classList.remove(window.bs_data.hidden_class);

                if (progressElements.length > 0) {
                    progressElements.forEach(function (element, index) {
                        if (element.classList.contains('required') && element.type === "radio") {
                            if (element.attributes['data-id'] !== undefined && element.attributes['data-id'].value !== undefined) {
                                let radioGroupId = element.attributes['data-id'].value;
                                let radioGroupContainer = document.getElementById(radioGroupId);
                                let radioGroup = radioGroupContainer.querySelectorAll('input');
                                if (radioGroup.length > 0) {
                                    let isChecked = false;
                                    radioGroup.forEach(function (item, index) {
                                        if (item.checked) {
                                            isChecked = true;
                                        }
                                    })
                                    if (!isChecked) {
                                        if (errorList.indexOf(element.attributes['data-id'].value) === -1) {
                                            errorList.push(element.attributes['data-id'].value);
                                        }
                                    }
                                }

                            }
                        } else if (element.classList.contains('required') && element.value === "") {
                            errorList.push(element.id);
                        }
                    });
                }

                if (bidspiritUser !== undefined && bidspiritUser.email !== undefined) {
                    if (errorList.length > 0) {
                        const firstField = document.getElementById(errorList[0]);

                        if (firstField !== undefined) {
                            scrollTo(firstField, 165);
                        }

                        errorList.forEach(function (item, index) {
                            const input = document.getElementById(item);
                            const errorInput = document.getElementById("error-" + item);

                            if (input.classList.contains('bp-radio-group')) {
                                let radioGroup = input.querySelectorAll('input');
                                if (radioGroup.length > 0) {
                                    let isChecked = false;
                                    radioGroup.forEach(function (item, index) {
                                        if (item.checked) {
                                            isChecked = true;
                                        }
                                    })
                                    if (!isChecked) {
                                        errorInput.classList.remove(window.bs_data.hidden_class);
                                        errorInput.classList.add('bp-error');
                                    }
                                }
                            } else {
                                errorInput.classList.remove(window.bs_data.hidden_class);
                                errorInput.classList.add('bp-error');
                            }

                        });

                        loader.classList.add(window.bs_data.hidden_class);
                    } else {
                        const userInfo = document.querySelector("#bp-submission-form");
                        const formData = new FormData(userInfo);
                        formData.append('email', bidspiritUser.email);

                        const response = await fetch('/wp-json/bidspirit/v1/submission/form', {
                            headers: {"X-WP-Nonce": ScoreSettings.nonce},
                            method: "POST",
                            body: formData,
                        });

                        if (response.ok) {
                            let result = await response.json();
                            loader.classList.add(window.bs_data.hidden_class);
                            if (result.result === 1) {
                                loadTemplate(wrapper, "submission-tu-template", {}, true, function () {
                                    const againAction = document.getElementById("submissions-again");
                                    if (!!againAction) {
                                        againAction.addEventListener("click", function (event) {
                                            event.preventDefault();

                                            loadTemplate(wrapper, "submission-form-template", {}, true, function () {
                                                action(wrapper);
                                            });
                                        })
                                    }
                                });
                            } else {
                                console.log("Submission form not submitted");
                            }

                            console.log("result", result);
                        } else {
                            loader.classList.add(window.bs_data.hidden_class);
                            alert("HTTP error: " + response.status);
                        }
                    }
                } else {
                    MicroModal.show("modal-login", microModalInitConfig());
                }
            });
        }

        if (progressElements.length > 0) {
            function calcProgress(progressElements, progressBar, progressBarCounter) {
                let counter = 0,
                    total = progressElements.length,
                    result = 0;
                progressElements.forEach(element => {
                    if (!element.classList.contains('required')) {
                        total--;
                    } else if (element.attributes['type'] !== undefined && element.attributes['type'].value === "radio" && element.checked) {
                        counter++;
                    } else if (element.attributes['type'] !== undefined && element.attributes['type'].value === "radio" && !element.checked) {
                        total--;
                    } else {
                        if (element.value !== "") {
                            counter++;
                        }
                    }
                })

                result = Math.floor((counter / total) * 100);
                progressBar.style.cssText = `
                  width: ${result}%;
                `;

                progressBarCounter.innerHTML = " " + result.toString() + "%";
            }

            const progressBar = document.querySelector('.bp-progress-bar .bp-progress-bar__inner');
            const progressBarCounter = document.querySelector('.bp-progress-bar p span');
            progressElements.forEach(function (elem, index) {
                elem.addEventListener('change', async function (event) {
                    const input = event.target;
                    let errorInput = "";
                    if (input.attributes['data-id'] !== undefined && input.attributes['data-id'].value !== undefined) {
                        errorInput = document.getElementById("error-" + input.attributes['data-id'].value);
                    } else {
                        errorInput = document.getElementById("error-" + input.id);
                    }

                    if (input.value !== "") {
                        errorInput.classList.remove('bp-error');
                        errorInput.classList.add(window.bs_data.hidden_class);
                    }

                    calcProgress(progressElements, progressBar, progressBarCounter);
                })
            })
        }
    }

    function loadSubmissionForm() {
        let bidspiritUser = bidspiritApi.getBidspiritUser(),
            wrapper = $("#submissions-wrapper");

        if (bidspiritUser !== undefined && bidspiritUser.emailConfirmed === false) {
            loadTemplate(wrapper, "submission-approved-template", {}, true, function () {
                action(wrapper);
            });
        } else if (bidspiritUser !== undefined && bidspiritUser.emailConfirmed === true) {
            loadTemplate(wrapper, "submission-form-template", {}, true, function () {
                action(wrapper);
            });
        } else {
            loadTemplate(wrapper, "submission-pre-template", {}, true, function () {
                MicroModal.init();
            });
        }
    }

    document.addEventListener("DOMContentLoaded", function(event) {
        $(window).on('bp:after-init', function() {
            loadSubmissionForm();
        });

        $(window).on('bp:after-login', function() {
            loadSubmissionForm();
        });
    });
})(jQuery);