import documentReady from '@assets/js/documentReady';
import FixedContentOnScroll from '../../fixed-content';
import axiosApi from '@assets/js/axios-api';
import { CancelToken } from 'axios';

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

 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();
      saveCartFields();
      if (data.checkout) {
        window.location = data.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;
      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(err => 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');
  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);
  }
}

export function saveCartFields() {
  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 }) => {
    return data;
  });
}

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 container = element.closest('.js-order-by-item');
  const productsLength = document.querySelectorAll('.js-order-by-item').length;

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

  sendAjaxFromForm({
    action: action,
    method: 'GET',
  })
    .then(() => container.remove())
    .catch(err => console.log(err, err.response));
}
