//import { Loader } from "./loader.js";
import { showErrorModal, showSuccessModal } from "./modals.js";

class Form {
   static hideFormErrors(form) {
      const errorContainer = form.querySelector(".error-text");

      const errorFields = form.querySelectorAll(".error");

      errorFields.forEach((field) => {
         field.classList.remove("error");
      });

      if (errorContainer) {
         errorContainer.innerHTML = "";
      }
   }

   static initRules(form, formData) {
      const requiredFields = form.querySelectorAll(".js-required");

      if (requiredFields.length) {
         const required = {};
         requiredFields.forEach((el) => {
            required[el.name] = JSON.parse(el.dataset.rules);
         });

         const strRules = JSON.stringify(required);

         formData.append("validate_rules", strRules);
      }

      return formData;
   }

   static showFormErrors(errors, form) {
      const errorContainer = form.querySelector(".error-text");

      if (!errorContainer) return;

      errorContainer.innerHTML = "";

      Object.values(errors).forEach((text) => {
         const item = document.createElement("div");

         item.textContent = text;

         errorContainer.append(item);
      });
   }

   static initForms(defaultForms = null) {
      const forms = defaultForms || document.querySelectorAll(".js-form");
      forms.forEach((form) => {
         form.addEventListener("submit", (event) => {
            this.formSubmitHandler(event, {
               beforeSend: (formData) => {
                  // Loader.showLoader();
               },
               finallySend: () => {
                  // Loader.hideLoader();
               },
            });
         });
      });

      document.querySelectorAll("#category-filter input[type=checkbox]").forEach((input) => {
         input.addEventListener("change", function () {
            console.log(input);

            const form = document.getElementById("category-filter");
            const event = new Event("change", { bubbles: true });
            form.dispatchEvent(event);
         });
      });
   }

   static validateForm(form) {
      let isValid = true;

      const errors = {};

      const requiredFields = form.querySelectorAll(".js-required");

      requiredFields.forEach((field) => {
         const rules = JSON.parse(field.dataset.rules || "{}");
         console.log(rules);

         const value = field.value.trim();

         const fieldName = field.name;

         // Имя

         if (fieldName === "fio") {
            if (!value) {
               errors[fieldName] = "Укажите ваше имя";
            } else if (value.length < Number(rules.minLength || 2)) {
               errors[fieldName] = "Имя не короче 2 символов";
            }
         }

         // Телефон

         if (fieldName === "phone") {
            if (!value) {
               errors[fieldName] = "Введите номер телефона";
            } else {
               const clearPhone = value.replace(/\D/g, "");

               if (clearPhone.length !== 11) {
                  errors[fieldName] = "Введите корректный номер телефона";
               }
            }
         }

         // Если ошибка

         if (errors[fieldName]) {
            isValid = false;

            field.parentElement.classList.add("error");
         }
      });

      this.showFormErrors(errors, form);

      return isValid;
   }

   /**
    *
    * @param {Event} e
    */
   static formSubmitHandler(e, callBack = null) {
      e.preventDefault();

      const form = e.target;
      let formData = new FormData(form);

      this.hideFormErrors(form);

      const isValid = this.validateForm(form);

      if (!isValid) {
         return;
      }

      formData = this.initRules(form, formData);

      const action = form.dataset.action ?? "form_submit";
      formData.append("action", action);

      console.log([...formData.entries()]);

      const props = {
         bubbles: true,
      };

      if (callBack && callBack.hasOwnProperty("beforeSend")) {
         callBack.beforeSend(formData);
      }

      const dataCallTouch = {};

      for (let [key, value] of formData) {
         dataCallTouch[key] = value;
      }

      fetch("/wp-admin/admin-ajax.php", {
         method: "POST",
         body: formData,
      })
         .then((response) => {
            return response.json();
         })
         .then((response) => {
            if (response.success) {
               form.reset();

               if (callBack && callBack.hasOwnProperty("afterSend")) {
                  callBack.afterSend(response);
               } else {
                  Fancybox.close();

                  showSuccessModal();
               }

               props.detail = {
                  form,
                  response,
                  action,
                  dataCallTouch,
               };

               const formSubmitEvent = new CustomEvent("lz-form-submit-success", props);
               document.dispatchEvent(formSubmitEvent);
            } else {
               const errors = response.data;

               if (callBack && callBack.hasOwnProperty("afterError")) {
                  callBack.afterError(response);
               } else {
                  if (errors.message) {
                     showErrorModal();
                  }

                  this.showFormErrors(errors, form);
               }
            }
         })
         .catch((err) => {
            console.log(err);
            showErrorModal();
         })
         .finally(() => {
            if (callBack && callBack.hasOwnProperty("finallySend")) {
               callBack.finallySend();
            }
         });
   }
}

export { Form };
