import documentReady from '@assets/js/documentReady';
import axios from 'axios';
import { del } from 'vue';

let data = {};
let elements = {};
let updatingProducts = {}; 

documentReady(() => {
  const header = document.querySelector('.js-header');
  const cartElement = header.querySelector('.js-header__cart');
  const sidecartButton = header.querySelector('.js-header__side');

  elements = {
    header,
    main: header.querySelector('.js-header__main'),
    logo: header.querySelector('.js-header__logo'),
    dropdown: header.querySelectorAll('.js-header__dropdown'),
    search: header.querySelector('.js-header__search'),
    searchFixed: header.querySelector('.js-search-fixed'),
    searchIcon: header.querySelector('.js-header__search i'),
    searchContainer: header.querySelector('.js-header__search-container'),
    searchInput: header.querySelector('.js-header__search-entry'),
    searchBtn: header.querySelector('.js-header__search-btn'),
    searchDropdown: header.querySelector('.js-header__search-dropdown'),
    searchSuggestion: header.querySelector('.js-header__search-suggestion'),

    cart: cartElement,
    cartContainer: cartElement ? cartElement.nextElementSibling : null,

    sidecartButton,
  };

  data = {
    lastScrollTop: 0,
    baseUrl: document.querySelector('base').href,
  };

  handleHeaderScroll();
  window.addEventListener('resize', handleHeaderScroll);
  window.addEventListener('load', resizeLogo);

  handleDropdown();
  handleCart();
  handleSearch();

  handleSidecart();
});

function createMask() {
  resetMask();

  const mask = document.createElement('div');
  mask.classList.add('overlay', 'overlay-black-1');
  mask.style.zIndex = '100';
  document.body.appendChild(mask);
  mask.addEventListener('click', resetMask);
  if (window.innerWidth > 992) {
    window.addEventListener('scroll', resetMask);
  }

  elements.mask = mask;
}

function resetMask() {
  const { mask, searchInput, searchDropdown, searchContainer } = elements;

  if (mask) {
    mask.remove();
    elements.mask = '';
  }

  if (!searchDropdown.classList.contains('hidden')) {
    searchInput.blur();
  }

  searchDropdown.classList.add('hidden');
  searchContainer.removeAttribute('style');

  const { dropdown } = elements;
  for (const dropdownItem of dropdown) {
    const dropdownContainer = dropdownItem.nextElementSibling;
    dropdownContainer.classList.add('hidden');
  }
}

function handleHeaderScroll() {

  resizeLogo(event);

  window.removeEventListener('scroll', handleHeaderFixed);
  window.addEventListener('scroll', handleHeaderFixed);
}

function resizeLogo() {
  if (event && event.currentTarget.innerWidth < 700 && document.querySelector('#logo_responsivo')) {
    const newWidth = document.querySelector('#logo_responsivo').getAttribute('width');
    const newHeigth = document.querySelector('#logo_responsivo').getAttribute('height');
    const newSrc = document.querySelector('#logo_responsivo').getAttribute('src');

    document.querySelector('#logo').setAttribute('width', newWidth + 'px')
    document.querySelector('#logo').setAttribute('heigth', newHeigth + 'px');
    document.querySelector('#logo').setAttribute('src', newSrc);
  }

  if (event && event.currentTarget.innerWidth >= 700 && document.querySelector('#logo_original')) {
    const newWidth = document.querySelector('#logo_original').getAttribute('width');
    const newHeigth = document.querySelector('#logo_original').getAttribute('height');
    const newSrc = document.querySelector('#logo_original').getAttribute('src');

    document.querySelector('#logo').setAttribute('width', newWidth + 'px')
    document.querySelector('#logo').setAttribute('heigth', newHeigth + 'px');
    document.querySelector('#logo').setAttribute('src', newSrc);
  }
}

function handleHeaderFixed() {
  const { header, main, logo } = elements;
  const scrollTop = window.scrollY;

  if (scrollTop > header.offsetHeight + header.offsetTop) {
    header.style.height = `${header.offsetHeight}px`;
    main.classList.add('header__main--fixed');
    if (logo) {
      logo.classList.add('header__logo--retract');
    }
  } else {
    header.removeAttribute('style');
    main.classList.remove('header__main--fixed', 'header__main--transition');
    if (logo) {
      logo.classList.remove('header__logo--retract');
    }
  }

  if (scrollTop > header.offsetHeight + header.offsetTop * 2) {
    main.classList.add('header__main--transition');
  }

  if (scrollTop < header.offsetHeight + header.offsetTop * 2) {
    main.classList.remove('header__main--visible', 'shadow-medium');
    return;
  }

  if (scrollTop === data.lastScrollTop) return;

  if (scrollTop < data.lastScrollTop || main.classList.contains('header__main--fixed')) {
    main.classList.add('header__main--visible', 'shadow-medium');
  }

  data.lastScrollTop = scrollTop;
}

// dropdown do carrinho flutuante
function handleDropdown() {
  const { dropdown, searchContainer } = elements;

  for (const dropdownItem of dropdown) {
    dropdownItem.addEventListener('click', () => {

      const dropdownNextElement = dropdownItem.nextElementSibling;

      if (dropdownNextElement.classList.contains('hidden')) {
        createMask();
        searchContainer.style.zIndex = 90;
        dropdownNextElement.classList.remove('hidden');
      } else {
        resetMask();
      }
    });
  }
}

function handleSidecart() {
  const { sidecartButton } = elements;
  if (!sidecartButton) return;

  sidecartButton.addEventListener('click', () => {
    const event = new CustomEvent('toggle-sidecart');
    window.dispatchEvent(event);
  });
}

function handleCart() {
  const { cart, cartContainer } = elements;

  if (!cart || !cartContainer) return;
  const cartType = cartContainer.getAttribute('data-cart-type');

  if (cartType != "2") {
    cart.addEventListener('click', async () => {

      const currentCartContainer = cartContainer.innerHTML;
      cartContainer.innerHTML =
        '<span class="text-medium text-bold text-dark visible-block text-center">Carregando...</span>';

      try {
        const { data } = await axios.get('index.php?route=module/cart');      
        cartContainer.innerHTML = data;
        
        const decrementButtons = cartContainer.querySelectorAll('.btn-decrement');
        const incrementButtons = cartContainer.querySelectorAll('.btn-increment');
        const quantityInputs = cartContainer.querySelectorAll('.quantity-input');
        const removeButtons = cartContainer.querySelectorAll('.btn-remove-product');

        decrementButtons.forEach(button => {
          button.addEventListener('click', handleQuantityChange);
        });

        incrementButtons.forEach(button => {
          button.addEventListener('click', handleQuantityChange);
        });

        quantityInputs.forEach(input => {
          input.addEventListener('change', handleManualQuantityChange);
          input.addEventListener('input', handleQuantityInput);
          input.addEventListener('keydown', blockInvalidKeys);
        });

        removeButtons.forEach(button => {
          button.addEventListener('click', removeProduct);
        })

      } catch (error) {
        cartContainer.innerHTML = currentCartContainer;
        console.error('Error loading cart:', error);
      }
    });
  }
}

async function handleQuantityChange(event) {
  const button = event.currentTarget;
  const productItem = button.closest('[data-product-id]');
  const productId = productItem.dataset.productId;
  const input = productItem.querySelector(`input[name="quantity[${productId}]"]`);

  if (updatingProducts[productId]) return; 
  updatingProducts[productId] = true;

  const previousQuantity = parseInt(input.dataset.previousQuantity, 10) || parseInt(input.value, 10) || 0;
  let newQuantity = parseInt(input.value, 10) || 0;

  if (button.classList.contains('btn-increment')) {
    newQuantity = previousQuantity + 1;
  } else if (button.classList.contains('btn-decrement') && previousQuantity > 1) {
    newQuantity = previousQuantity - 1;
  }

  input.value = newQuantity;

  try {
    await updateProductQuantity(productId, newQuantity);

    input.dataset.previousQuantity = newQuantity;
    updateFloatingCart(); 

  } catch (error) {
    console.error('Erro ao atualizar quantidade:', error);
    input.value = previousQuantity;
    input.dataset.previousQuantity = previousQuantity;
  }
  finally {
    updatingProducts[productId] = false;
  }
}

function handleQuantityInput(event) {
  const input = event.target;

  input.value = input.value.replace(/[^0-9]/g, '');

  if (input.value === '' || input.value === '0') {
    input.value = '1';
  }
}

function blockInvalidKeys(event) {
  const invalidKeys = ['.', ',', '-', '+', 'e', 'E'];
  if (invalidKeys.includes(event.key)) {
    event.preventDefault();
  }
}

async function handleManualQuantityChange(event) {
  const input = event.currentTarget;
  const productId = input.name.match(/\[([^\]]+)\]/)[1];

  const previousQuantity = parseInt(input.dataset.previousQuantity, 10) || parseInt(input.value, 10) || 1;

  let newQuantity = parseInt(input.value, 10);

  if (isNaN(newQuantity) || newQuantity < 1) {
    newQuantity = 1;
  }

  input.value = newQuantity;

  if (updatingProducts[productId]) return; 
  updatingProducts[productId] = true;

  try {
    await updateProductQuantity(productId, newQuantity);
    
    input.dataset.previousQuantity = newQuantity;
    updateFloatingCart(); // recalcula total


  } catch (error) {
    console.error('Failed to update product quantity:', error);
    input.value = previousQuantity;
    input.dataset.previousQuantity = previousQuantity;
  }
  finally {
    updatingProducts[productId] = false;
  }
}

async function updateProductQuantity(productId, newQuantity) {
  const formData = new FormData();
  formData.append(`quantity[${productId}]`, newQuantity);

  try {
    const response = await axios({
      url: 'index.php?route=checkout/cart&ajax=1',
      method: 'post',
      data: formData,
      headers: {
        'Content-type': 'multipart/form-data'
      }
    });

    const data = response.data;
    const input = document.querySelector(`input[name="quantity[${productId}]"]`);

    if (data.success || (!data.error_warning && !data.attention)) {
      handlerNotification(data);
      if (input) {
        input.setAttribute('data-previous-quantity', newQuantity);
      }
    } else {
      handlerNotification(data);
      restorePreviousQuantity(productId);
    }
  } catch (error) {
      console.error('Erro ao atualizar a quantidade:', error);
      restorePreviousQuantity(productId);
  }
}

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 updateFloatingCart(delta = null) {
  const floatingCartElement = document.querySelector('.floatingcart-quantity');

  if (delta !== null) {
    let totalCount = parseInt(floatingCartElement.textContent, 10) || 0;
    totalCount += delta;
    floatingCartElement.textContent = totalCount;

  } else {
    const totalQuantity = Array.from(document.querySelectorAll('.quantity-input'))
      .reduce((sum, input) => sum + (parseInt(input.value, 10) || 0), 0);

    floatingCartElement.textContent = totalQuantity;
  }
}

function restorePreviousQuantity(productId) {
  const input = document.querySelector(`input[name="quantity[${productId}]"]`);

  if (input) {
    const previousQuantity = input.getAttribute('data-previous-quantity');
    if (previousQuantity !== null) {
      input.value = previousQuantity;
    }
  }
}

async function removeProduct(event) {
  const button = event.currentTarget;
  const productItem = button.closest('[data-product-id]');
  const productContainer = button.closest('.product-container');
  const productId = productItem.dataset.productId;
  const input = productItem.querySelector(`input[name="quantity[${productId}]"]`);

  if (!productItem || !productContainer || !input) return;

  const currentQuantity = parseInt(input.value, 10) || 0;

  // evita múltiplas remoções simultâneas do mesmo produto
  if (updatingProducts[productId]) return;
  updatingProducts[productId] = true;

  button.style.pointerEvents = "none";

  try {
    await updateProductQuantity(productId, 0);
    productContainer.remove();
    updateFloatingCart(-currentQuantity);

    const visibleProducts = document.querySelectorAll('.product-container');
    if (visibleProducts.length === 3) {
      updateCartContent();
    }

  } catch (error) {
    console.error('Erro ao remover produto:', error);
  }

  finally {
    delete updatingProducts[productId];
    button.style.pointerEvents = "";
  }
}

async function updateCartContent() {

  const { cartContainer } = elements;
  const currentCartContainer = cartContainer.innerHTML;
  cartContainer.innerHTML = '<span class="text-medium text-bold text-dark visible-block text-center">Carregando...</span>'

  try {
    const { data } = await axios.get('index.php?route=module/cart');
    cartContainer.innerHTML = data;

    cartContainer.querySelectorAll('.btn-remove-product').forEach(button => {
      button.addEventListener('click', removeProduct);
    });
    cartContainer.querySelectorAll('.btn-decrement').forEach(button => {
      button.addEventListener('click', handleQuantityChange);
    });
    cartContainer.querySelectorAll('.btn-increment').forEach(button => {
      button.addEventListener('click', handleQuantityChange);
    });
    cartContainer.querySelectorAll('.quantity-input').forEach(input => {
      input.addEventListener('change', handleManualQuantityChange);
      input.addEventListener('input', handleQuantityInput);
      input.addEventListener('keydown', blockInvalidKeys);
    });

  } catch (error) {
    cartContainer.innerHTML = currentCartContainer;
    console.error('Erro ao carregar carrinho:', error);
  }
}

function handleSearch() {
  const { baseUrl } = data;
  const { search, searchIcon, searchContainer, searchInput, searchBtn, searchDropdown, searchSuggestion, searchFixed } = elements;

  searchInput.disabled = false;

  if (searchFixed.classList.contains('active_searchbar')) {
    search.style.display = 'none';
    searchContainer.classList.remove('hidden-sm-down');
    searchIcon.classList.remove('fa-search');
    searchIcon.classList.add('fa-times');
  }
  else if (searchFixed.classList.contains('inactive_searchbar')) {
    search.addEventListener('click', () => {
      if (searchContainer.classList.contains('hidden-sm-down')) {
        searchContainer.classList.remove('hidden-sm-down');
        searchIcon.classList.remove('fa-search');
        searchIcon.classList.add('fa-times');
      } else {
        searchContainer.classList.add('hidden-sm-down');
        searchIcon.classList.add('fa-search');
        searchIcon.classList.remove('fa-times');
        resetMask();
      }
    });
  }

  searchInput.addEventListener('focus', () => {
    createMask();
    handleInputTyping();
    searchDropdown.classList.remove('hidden');
  });

  searchBtn.addEventListener('click', () => {
    if (searchInput.value.length > 0) {
      searchBtn.disabled = true;
      redirect();
    } else {
      createMask();
      searchInput.focus();
      searchDropdown.classList.remove('hidden');
    }
  });

  const renderProducts = (products, seeAll) => {
    searchSuggestion.innerHTML = '';

    for (let i = 0; i < products.length; i++) {
      const { href, name, image, history } = products[i];

      const a = document.createElement('a');
      a.classList.add(
        'flex',
        'flex-row',
        'nowrap-xs',
        'middle-xs',
        'vertical-padding-small',
        'horizontal-padding-medium'
      );
      a.href = href;

      const thumb = document.createElement('div');
      thumb.classList.add('flex-auto', 'right-margin-medium');

      if (history) {
        const i = document.createElement('i');
        i.classList.add('fas', 'fa-history', 'text-medium', 'vertical-margin-small');
        thumb.appendChild(i);
      } else {
        const img = document.createElement('img');
        img.width = 40;
        img.height = 40;
        img.src = image;
        thumb.appendChild(img);
      }
      a.appendChild(thumb);

      const content = document.createElement('div');
      content.classList.add('flex-1');

      const span = document.createElement('span');
      span.classList.add('visible-block', 'text-medium');
      span.textContent = name;
      content.appendChild(span);

      a.appendChild(thumb);
      a.appendChild(content);
      searchSuggestion.appendChild(a);
    }

    if (seeAll) {
      const a = document.createElement('a');
      a.classList.add('visible-block', 'text-medium', 'text-center', 'padding-medium');
      a.href = `${baseUrl}index.php?route=product/search&search=${encodeURIComponent(searchInput.value.trim())}`;

      const span = document.createElement('span');
      span.textContent = `Ver todos os resultados para "${searchInput.value}"`;

      a.appendChild(span);
      searchSuggestion.appendChild(a);
    }
  };

  const renderMessage = text => {
    searchSuggestion.innerHTML = '';
    const span = document.createElement('span');
    span.classList.add('text-medium', 'text-center', 'visible-block', 'padding-medium');
    span.textContent = text;
    searchSuggestion.appendChild(span);
  };

  const redirect = () => {
    const suggestionActiveItem = searchSuggestion.querySelector('a.active');

    if (suggestionActiveItem) {
      location = suggestionActiveItem.href;
      return;
    }

    if (searchInput.value.trim().length > 0) {
      location = `${baseUrl}index.php?route=product/search&search=${encodeURIComponent(searchInput.value.trim())}`;
    }
  };

  const handleInputTyping = () => {
    let suggestionActiveItem = -1;
    searchInput.addEventListener('keydown', event => {
      const suggestionList = searchSuggestion.querySelectorAll('a');
      const suggestionAmount = suggestionList.length;

      const pressedKey = {
        Enter() {
          redirect();
        },
        ArrowDown() {
          suggestionActiveItem = suggestionActiveItem >= suggestionAmount - 1 ? 0 : suggestionActiveItem + 1;
          for (const suggestionItem of suggestionList) {
            suggestionItem.classList.remove('active');
          }
          suggestionList[suggestionActiveItem].classList.add('active');
        },
        ArrowUp() {
          searchInput.selectionStart = searchInput.selectionEnd = searchInput.value.length; // Insere o cursor no final do input
          suggestionActiveItem = suggestionActiveItem <= 0 ? suggestionAmount - 1 : suggestionActiveItem - 1;
          for (const suggestionItem of suggestionList) {
            suggestionItem.classList.remove('active');
          }
          suggestionList[suggestionActiveItem].classList.add('active');
        },
        Escape() {
          resetMask();
        },
      };

      if (pressedKey[event.key]) {
        pressedKey[event.key]();
      }
    });

    let timeoutSearch = '';
    searchInput.addEventListener('input', () => {
      if (searchInput.value.length < 3) {
        handleHistory();
        return;
      }

      renderMessage('Procurando...');

      if (timeoutSearch) clearTimeout(timeoutSearch);

      timeoutSearch = setTimeout(async () => {
        await handleSearchSuggestion();
      }, 2000);
    });
  };

  const handleSearchSuggestion = async () => {
    try {
      const { data } = await axios.get('index.php?route=product/search/getSearchSuggestion', {
        params: {
          search: searchInput.value,
        },
      });

      if (data.products.length > 0) {
        renderProducts(data.products, true);
      } else {
        renderMessage(`Não encontramos nada relacionado a "${searchInput.value}"`);
      }
    } catch (err) {
      renderMessage(`Desculpe, tivemos algum problema ao pesquisar.`);
    }
  };

  const decodeHTML = html => {
    const textarea = document.createElement('textarea');
    textarea.innerHTML = html;
    return textarea.value;
  };

  const handleHistory = () => {
    const cookie = getCookie('search_terms');
    let history = false;

    if (cookie !== '') {
      history = JSON.parse(decodeURIComponent(decodeURIComponent(cookie)));
    }

    if (history === false) {
      renderMessage('Escreva algo para pesquisar...');
      return;
    }

    if (searchInput.value.length === 0) {
      let products = [];
      for (var i = 0; i < history.length; i++) {
        products.push({
          name: decodeHTML(history[i]),
          href: `${baseUrl}index.php?route=product/search&search=${encodeURIComponent(decodeHTML(history[i]))}`,
          history: true,
        });
      }
      renderProducts(products, false);
    }
  };

  handleHistory();

}

document.addEventListener('DOMContentLoaded', function () {
  const btnToggle = document.getElementById('btn-toggle-sidecart');

  if (btnToggle) {
    btnToggle.addEventListener('click', function (event) {
      event.stopPropagation();
      window.dispatchEvent(new CustomEvent('toggle-sidecart'));
    });
  }
});

window.updateFloatingCart = updateFloatingCart;