import documentReady from "@assets/js/documentReady";
import FixedContentOnScroll from "../../fixed-content";
import axiosApi from "@assets/js/axios-api";
import googleAnalytics from "@assets/js/googleAnalytics";
import googleTagManager from "@assets/js/googleTagManager";
import { addToBuyLater } from "../base/buy_later";
import { CancelToken } from "axios";

export function init() {
  documentReady(() => {
    fixAsideContent();
    quantity();
    finishCart();
    removeProduct();
    buyLater();
    validateObservationOnLoad();
    googleAnalyticsViewCart();
  });
}

function googleAnalyticsViewCart() {
  const cartCheckout = document.getElementById("checkout-cart-data");
  const data = JSON.parse(cartCheckout.dataset.wishlist);
  googleAnalytics("view_cart", data);
}

function validateObservationOnLoad() {
  const div = document.querySelector("#js-order-by-list");

  if (div) {
    const getData = document
      .querySelector("#js-order-by-list")
      .getAttribute("data");
    const data = getData ? JSON.parse(getData) : null;

    if (data) {
      notificationMsg(
        "Alguns campos estão incorretos, corrija os campos em vermelho!",
        "error"
      );

      document.querySelectorAll("[error-obs-lista-id]").forEach(element => {
        let inputListId = element.getAttribute("error-obs-lista-id");

        data.forEach(listId => {
          if (listId === inputListId) {
            element.textContent = "O campo não pode ser vazio";
            element.classList.remove("hidden");
          }
        });
      });

      document.querySelectorAll("[data-obs-lista-id]").forEach(element => {
        let spanListId = element.getAttribute("data-obs-lista-id");

        data.forEach(listId => {
          if (spanListId == listId) {
            element.classList.add("error-field-list-school");
            element.addEventListener("input", inputTextchange);
          }
        });
      });
    }
  }
}

export function updateCartList() {
  const { action, method } = {
    action: "index.php?route=checkout/cart/onReloadCartList",
    method: "GET"
  };

  const requestConfig = {
    url: `${action}&ajax=1`,
    method: method
  };

  axiosApi(requestConfig).then(({ data }) => {
    let listCart = document.getElementById("js-order-by-list");
    let contextData = sendAjaxFromForm({
      action: `${window.location.href}&ajax=1`,
      method: "GET"
    }).then(function () {
      listCart.innerHTML = data;
      init();
      initActionProductBoxCartList();
    });
  });
}

function finishCart() {
  const cartCheckout = document.getElementById("checkout-cart-data");
  if (cartCheckout) {
    const data = JSON.parse(cartCheckout.dataset.checkoutCart);
    handlerNotification(data);

    const btnCheckout = document.getElementById("button-checkout");
    btnCheckout.addEventListener("click", function (event) {
      event.preventDefault();
      let checkout = data.checkout;

      saveCartFields(checkout);
    });
  }
}

function fixAsideContent() {
  const fixedOnTop = document.querySelector(".js-fixed-on-top");
  if (fixedOnTop) {
    new FixedContentOnScroll(fixedOnTop, {
      discountTop: [document.querySelector(".js-header__main")]
    });
  }
}

function quantity() {
  const quantityForms = document.querySelectorAll(".js-quantity-form");
  for (let i = 0; i < quantityForms.length; i++) {
    const form = quantityForms[i];
    const container = form.closest(".js-order-by-item");
    const productTotalElement = container.querySelector(".js-total");
    const input = container.querySelector("input");
    const imgLoading = document.createElement("img");
    imgLoading.src = "assets/img/loading-black.svg";
    imgLoading.setAttribute(
      "style",
      `
      width: 24px;
      height: 100%;
      right: -24px;
      position: absolute;
      opacity: 0;
      transition: 1s linear;
      `
    );

    const callback = ({ cartlist: cartList }) => {
      const { productId, keyTipo, keyLista } = form.dataset;
      const lista = cartList[keyTipo][keyLista];
      const product = lista.products.find(({ product_id }) => {
        return product_id == productId;
      });
      if (!product) return;

      const cartListStock = container.querySelector(".cart-list-stock");
      if (cartListStock) {
        if (product.stock) {
          cartListStock.classList.add("hidden");
        } else {
          cartListStock.classList.remove("hidden");
        }
      }

      input.value = product.quantity;
      container.dataset.quantity = product.quantity;
      if (product.total !== false) {
        productTotalElement.innerHTML = product.total;
        container.dataset.totalPrice = product.total_value;

        refreshST(cartList);
      }

      imgLoading.remove();
    };

    let timer;
    const cancelTokens = {};

    input.oninput = function () {
      // if (input.value === '') return;
      if (input.value < 1 || input.value == "" || input.value == null)
        return (input.value = 1);
      const token = cancelTokens[input.name];

      if (token) {
        token.cancel();
      }

      const cancelToken = CancelToken.source();
      cancelTokens[input.name] = cancelToken;

      clearTimeout(timer);
      timer = setTimeout(() => {
        input.parentNode.parentNode.appendChild(imgLoading);
        imgLoading.style.opacity = 1;
        sendAjaxFromForm(form, cancelToken)
          .then(callback)
          .catch(function (err) {
            imgLoading.remove();
            console.log(err, err.response);
          });
      }, 1000);
    };
  }
}

export function refreshST(cartList) {
  const st = ["st", "ipi", "fcpst"];

  for (let keyTipo in cartList) {
    const cartTipo = cartList[keyTipo];

    for (let keyLista in cartTipo) {
      const lista = cartTipo[keyLista];

      for (let keyProduto in lista.products) {
        const product = lista.products[keyProduto];

        const container = document.getElementById(product.product_id);
        const productTotalElement = container.querySelector(".js-total");
        productTotalElement.innerHTML = product.total;
        container.dataset.totalPrice = product.total_value;

        for (const st_name of st) {
          if (product[`${st_name}_valor_value`] != "N") {
            container.setAttribute(
              `data-value-${st_name}`,
              product[`${st_name}_valor_value`]
            );

            const stElement = container.querySelector(`.${st_name}_valor`);
            if (stElement) {
              stElement.innerHTML = product[`${st_name}_valor`];
            }
          } else {
            container.removeAttribute(`data-value-${st_name}`);

            const stElement = container.querySelector(`.${st_name}_valor`);
            if (stElement) {
              stElement.innerHTML = "";
            }
          }
        }
      }
    }
  }
}

function updateTotals(data) {
  let totals = data.totals;
  let valor_minimo = data.valor_minimo;

  if (!totals) return;

  if (!Array.isArray(totals)) {
    totals = Object.values(totals);
  }

  const totalsContainer = document.querySelector(".js-totals");
  const minValueContainer = document.querySelector(".min-value-container");
  const btnCheckout = document.querySelector(".btn-checkout");
  if (totals.length > 0) {
    totalsContainer.innerHTML = totals
      .map(
        total => `<div class="flex nowrap-xs between-xs middle-xs vertical-padding-x-small totals-value">
    <span class="text-medium text-gray right-padding-x-small">${total.title}</span>
    <span class="text-medium text-dark text-bold text-nowrap left-padding-x-small">${total.text}</span>
  </div>`
      )
      .join("");
  }

  btnCheckout.disabled = Boolean(valor_minimo);
  minValueContainer.innerHTML = valor_minimo ? valor_minimo : "";
}

export function handlerNotification(data) {
  const { success, attention, error_warning: errorWarning } = data;
  const message = errorWarning || attention || success || "";
  const type = errorWarning ? "warning" : "success";

  if (message.trim()) {
    window.notificationMsg(message, type);
  }
}

function inputTextchange(e) {
  if (e.target.value != "") {
    e.target.classList.remove("error-field-list-school");

    document.querySelectorAll("[error-obs-lista-id]").forEach(element => {
      let targetId = e.target.getAttribute("data-obs-lista-id");
      let listId = element.getAttribute("error-obs-lista-id");

      if (targetId == listId) {
        element.classList.add("hidden");
      }
    });
  }
}

export function saveCartFields(checkout) {
  let form = {
    url: "index.php?route=checkout/cart/saveListCartObs",
    method: "POST"
  };
  const requestConfig = form;

  const listObservations = document.querySelectorAll(".list_cart_obs");
  let obsDataForm = new FormData();
  if (listObservations.length > 0) {
    listObservations.forEach(function (observation, i) {
      obsDataForm.append("observations[]", [
        observation.dataset.obsListaId + "|",
        observation.value
      ]);
    });
  }

  return axiosApi({
    method: "POST",
    url: "index.php?route=checkout/cart/saveListCartObs",
    data: obsDataForm
  }).then(({ data }) => {
    if (data) {
      notificationMsg(
        "Alguns campos estão incorretos, corrija os campos em vermelho!",
        "error"
      );

      document.querySelectorAll("[error-obs-lista-id]").forEach(element => {
        let listId = element.getAttribute("error-obs-lista-id");

        data.forEach((error, key) => {
          if (Object.keys(error)[0] == listId) {
            element.textContent = String(error[Object.keys(error)[0]][0]);
            element.classList.remove("hidden");
          }
        });
      });

      document.querySelectorAll("[data-obs-lista-id]").forEach(element => {
        let listId = element.getAttribute("data-obs-lista-id");

        data.forEach((error, key) => {
          if (Object.keys(error)[0] == listId) {
            element.classList.add("error-field-list-school");
            element.addEventListener("input", inputTextchange);
          }
        });
      });
    } else {
      if (checkout) {
        window.location = checkout;
      }
    }
  });
}

export function sendAjaxFromForm(form, cancelToken = null) {
  const { action, method } = form;
  const requestConfig = {
    url: `${action}&ajax=1`,
    method
  };

  if (typeof form.tagName != "undefined") {
    requestConfig["data"] = new FormData(form);
  }
  if (cancelToken) {
    requestConfig["cancelToken"] = cancelToken.token;
  }

  return axiosApi(requestConfig).then(({ data }) => {
    handlerNotification(data);
    updateTotals(data);
    updateFloatingCartQuantity();
    return data;
  });
}

export function removeProductAjax(action, element) {
  const cartCheckout = document.getElementById("checkout-cart-data");
  const container = element.closest(".js-order-by-item");
  const productsLength = document.querySelectorAll(".js-order-by-item").length;

  const googleAnalyticsCodes = JSON.parse(cartCheckout.dataset.googleAnalytics);
  if (googleAnalyticsCodes) {
    const eventName = "remove_from_cart";
    const params = {
      currency: "BRL",
      items: [
        {
          item_id: container.dataset.code,
          item_name: container.dataset.name,
          price: container.dataset.unitPrice,
          currency: "BRL",
          quantity: container.dataset.quantity
        }
      ]
    };

    if (googleAnalyticsCodes.find(ga => ga === "gtag")) {
      googleAnalytics(eventName, params);
    }

    if (googleAnalyticsCodes.find(ga => ga === "gtm")) {
      googleTagManager(eventName, params);
    }
  }

  if (productsLength === 1) {
    return (window.location.href = action);
  }

  sendAjaxFromForm({
    action: action,
    method: "GET"
  })
    .then(() => {
      container.remove();
      hrShoppingCart();
    })

    .catch(err => console.log(err, err.response));
}

export function removeProduct() {
  const removeProductAll = document.querySelectorAll(".js-remove-product");
  if (removeProductAll) {
    for (const removeProduct of removeProductAll) {
      const TypeList = removeProduct.dataset.typelist;
      removeProduct.addEventListener("click", event => {
        if (TypeList == 0) {
          event.preventDefault();
        }
        event.stopPropagation();
        const item = removeProduct.closest(".js-order-by-item");
        removeProductAjax(removeProduct.href, removeProduct);
      });
    }
  }
}

export function buyLater() {
  const buyLaterAll = document.querySelectorAll(".js-buy-later");
  if (buyLaterAll) {
    for (const buyLaterProduct of buyLaterAll) {
      buyLaterProduct.addEventListener("click", event => {
        event.preventDefault();
        event.stopPropagation();
        const item = buyLaterProduct.closest(".js-order-by-item");
        const qty = item.querySelector(".js-quantity").value;
        const action = buyLaterProduct.href + "&quantity=" + qty;
        addToBuyLater(action, document.querySelector(".js-buy-later-list"));
        removeProductAjax(buyLaterProduct.dataset.remove, buyLaterProduct);
      });
    }
  }
}

export function hrShoppingCart() {
  let listsOfProducts = Array.from(document.getElementById('js-order-by-list').children);
  let listElement = listsOfProducts.filter(element => element.children.length > 0);

  listElement.forEach((element, index) => {
    if (index == 0) {
      let hrElement = element.querySelector('.cartListHr');

      if (hrElement) {
        hrElement.remove();
      }
    }
  });
}

function updateFloatingCartQuantity() {
  const floatingCartElement = document.querySelector('.floatingcart-quantity');
  // Seleciona todos os formulários de quantidade
  const forms = document.querySelectorAll('.js-quantity-form');

  let totalQuantity = 0;
  forms.forEach(form => {
    // Seleciona o input de quantidade dentro do formulário atual
    const input = form.querySelector('input[name^="quantity["]');
    if (input) {
      const productQuantity = parseInt(input.value, 10);
      if (!isNaN(productQuantity)) {
        totalQuantity += productQuantity;
      }
    }
  });

  floatingCartElement.textContent = totalQuantity;
}
