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

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

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();
    });
  });
}

async 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();

      saveCartFields(data);
    });
  }
}

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;
      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 handleListCartObs(e) {
  if (e.target.value.length > 0) {
    let listId = e.target.getAttribute('data-obs-lista-id');
    document.querySelector(`input[data-obs-lista-id='${listId}']`).classList.remove('error-field-list-school');
    document.querySelector(`label[data-obs-lista-id='${listId}']`).classList.add('hidden');
  }
}

export async function saveCartFields(cartCheckout) {
  const listObservations = document.querySelectorAll('.list_cart_obs');
  let observationData = [];
  let hasError = false;

  if (listObservations.length > 0) {
    listObservations.forEach(function (observation, i) {
      observationData.push({
        listId: observation.dataset.obsListaId,
        nameStudent: observation.value.trim()
      })
    });
  }

  await axiosApi({
    method: 'POST',
    url: 'index.php?route=checkout/cart/saveListCartObs',
    data: param({
      observations: observationData
    }),
  }).then(({ data }) => {
    if (data) {

      data.map((item) => {
        if (Object.values(item)[0]) {
          document.querySelector(`label[data-obs-lista-id='${Object.keys(item)[0]}']`).innerHTML = Object.values(item)[0];
          document.querySelector(`label[data-obs-lista-id='${Object.keys(item)[0]}']`).classList.remove('hidden');
          document.querySelector(`input[data-obs-lista-id='${Object.keys(item)[0]}']`).classList.add('error-field-list-school');
          document.querySelector(`input[data-obs-lista-id='${Object.keys(item)[0]}']`).addEventListener("input", handleListCartObs);

          hasError = true;
        }
      });

      if (hasError == true) {
        notificationMsg('Alguns campos estão incorretos. Corrija os campos em vermelho.', 'error');
      } else {
        if (cartCheckout.checkout) {
          window.location = cartCheckout.checkout;
        }
      }
    } else {
      if (cartCheckout.checkout) {
        window.location = cartCheckout.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);
    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())
    .catch(err => console.log(err, err.response));
}

export function removeProduct() {
  const removeProductAll = document.querySelectorAll('.js-remove-product');
  if (removeProductAll) {
    for (const removeProduct of removeProductAll) {
      removeProduct.addEventListener('click', event => {
        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);
      });
    }
  }
}