import documentReady from '@assets/js/documentReady';
import axios from 'axios';

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

documentReady(() => {
  const header = document.querySelector('.js-header');

  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'),
    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: header.querySelector('.js-header__cart'),
    cartContainer: header.querySelector('.js-header__cart').nextElementSibling,
  };

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

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

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

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

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 handleCart() {
  const { cart, cartContainer } = elements;

  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;
    } catch (error) {
      cartContainer.innerHTML = currentCartContainer;
    }
  });
}

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

  searchInput.disabled = false;

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