import { openAllAccordions, closeAllAccordions } from './accordeon.js';

// ##################################
// ### HANDLE FILTER SUBMENU TOGGLE
// ##################################
function handleSubmenuToggle() {
  const submenuToggle = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .filter-by-thematiques-submenu-toggle'
  );
  const submenuFilters = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .action-thematiques-filters-list'
  );

  if (!submenuToggle) return;

  submenuToggle.addEventListener('click', () => {
    const isSubmenuOpen = submenuToggle.getAttribute('aria-expanded');

    if (isSubmenuOpen === 'true') {
      return closeSubMenuFilters();
    } else {
      return openSubMenuFilters();
    }
  });

  // CLOSE SUBMENU IF CLICK OUTSIDE
  document.addEventListener('click', (e) => {
    const submenuGroup = document.querySelector('.filters-toolbar__action-thematiques-filters');

    const isClickInside = submenuGroup.contains(e.target);
    if (!isClickInside) {
      closeSubMenuFilters();
    }
  });

  // CLOSE SUBMENU IF ESCAPE KEY
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      closeSubMenuFilters();
    }
  });
}
function openSubMenuFilters() {
  const submenuToggle = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .filter-by-thematiques-submenu-toggle'
  );
  const submenuFilters = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .action-thematiques-filters-list'
  );
  submenuFilters.removeAttribute('hidden');
  submenuFilters.removeAttribute('aria-hidden');

  submenuToggle.setAttribute('active', '');
  submenuToggle.setAttribute('aria-expanded', 'true');
}
function closeSubMenuFilters() {
  const submenuToggle = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .filter-by-thematiques-submenu-toggle'
  );
  const submenuFilters = document.querySelector(
    '.filters-toolbar__action-thematiques-filters .action-thematiques-filters-list'
  );
  submenuFilters.setAttribute('hidden', '');
  submenuFilters.setAttribute('aria-hidden', '');

  submenuToggle.removeAttribute('active');
  submenuToggle.setAttribute('aria-expanded', 'false');
}

// ###########################
// ### DETAILS DEPLOY / CLOSE
// ###########################
function handleDeployCloseAllDetails() {
  const deployAllButton = document.querySelector('.filters-toolbar__action-button--deploy-all');
  const closeAllButton = document.querySelector('.filters-toolbar__action-button--close-all');
  const detailsContainers = document.querySelectorAll('details');

  if (!deployAllButton) return;

  deployAllButton.addEventListener('click', () => {
    openAllAccordions(detailsContainers);
    deployAllButton.setAttribute('hidden', true);
    closeAllButton.removeAttribute('hidden');
  });

  if (!closeAllButton) return;
  closeAllButton.addEventListener('click', () => {
    closeAllAccordions(detailsContainers);
    closeAllButton.setAttribute('hidden', true);
    deployAllButton.removeAttribute('hidden');
  });
}

// #################################
// ### UPDATE RESULTS AND DISPLAY
// ################################

function updatePostCountResults(totalPostsFound) {
  const resultAmountCounter = document.querySelector(
    '.filters-toolbar__posts-results-amount .results-amount '
  );
  resultAmountCounter.innerHTML = totalPostsFound;
}
function updateActiveFiltersViewer() {
  const activeFilters = document.querySelectorAll(
    '.filters-toolbar__action-thematiques-filter:checked'
  );
  if (activeFilters.length === 0) {
    const resetFiltersButton = document.querySelector(
      '.filters-toolbar__action-button--reset-filter'
    );
    resetFiltersButton.setAttribute('hidden', '');
  }

  const activeFiltersContainer = document.querySelector(
    '.filters-toolbar__active-filters-viewer .active-filters-button-container'
  );
  const previousButtons = activeFiltersContainer.querySelectorAll(
    '.filters-toolbar__action-button--active-filter-remover'
  );

  activeFiltersContainer.innerHTML = '';
  activeFilters.forEach((activeFilterCheckbox) => {
    const button = document.createElement('button');
    button.classList.add('filters-toolbar__action-button--active-filter-remover');

    const span = document.createElement('span');
    span.classList.add('sr-only');
    span.innerText = mainAppJsDynamicDatas.deleteFilter + ' :';
    button.appendChild(span);

    const buttonText = document.createTextNode(activeFilterCheckbox.getAttribute('data-title'));
    button.appendChild(buttonText);
    button.setAttribute('value', activeFilterCheckbox.getAttribute('value'));

    activeFiltersContainer.appendChild(button);

    button.addEventListener('click', () => {
      activeFilterCheckbox.checked = false;
      filterPosts();
    });
  });
}

// ###############################################
// ### HANDLE TOOLBAR ACTIVE FILTERS CLASS STATUS
// ###############################################

function setToolbarThematiqueFilterActive() {
  const toolBar = document.querySelector('.filters-toolbar--faq');
  toolBar.setAttribute('thematique-filter-active', '');
}
function setToolbarThematiqueFilterInactive() {
  const toolBar = document.querySelector('.filters-toolbar--faq');
  toolBar.removeAttribute('thematique-filter-active');
}

// ###########################
// ### POST FILTERTING
// ###########################

function handleFilterPosts() {
  const filters = document.querySelectorAll('.filters-toolbar__action-thematiques-filter');
  if (!filters) return;
  // HANDLE FILTERS
  filters.forEach((filter) => filter.addEventListener('click', filterPosts));

  // HANDLE "ALL" BUTTON
  const showAllButton = document.querySelector(
    '.filters-toolbar__action-thematiques-filter--show-all'
  );
  const loadAllButton = document.querySelector('.filters-toolbar__action-button--load-all');
  const resetFiltersButton = document.querySelector(
    '.filters-toolbar__action-button--reset-filter'
  );

  showAllButton.addEventListener('click', showAllPosts);
  loadAllButton.addEventListener('click', () => {
    closeSubMenuFilters();
    showAllPosts();
  });
  resetFiltersButton.addEventListener('click', () => {
    closeSubMenuFilters();
    showAllPosts();
  });
}
async function showAllPosts() {
  setToolbarThematiqueFilterInactive();
  const activeFilters = document.querySelectorAll(
    '.filters-toolbar__action-thematiques-filter:checked'
  );
  activeFilters.forEach((filter) => (filter.checked = false));
  const currentMainParentThematiqueId = document
    .querySelector('.post-question-page-container')
    .getAttribute('data-thematique-id');
  if (!currentMainParentThematiqueId) return;
  hydrateAllQuestions(currentMainParentThematiqueId);

  // Hide "load all" button
  const loadAllButton = document.querySelector('.filters-toolbar__action-button--load-all');
  loadAllButton.setAttribute('hidden', '');

  // Hide "reset all" button
  const resetAllButton = document.querySelector('.filters-toolbar__action-button--reset-filter');
  resetAllButton.setAttribute('hidden', '');

  updateActiveFiltersViewer();
  // Remove Toolbar Filter-Active Status
  const filtersToolbar = document.querySelector('.filters-toolbar--faq');
  filtersToolbar.removeAttribute('filter-active');
}
async function filterPosts() {
  setToolbarThematiqueFilterActive();
  const showAllPostsButton = document.querySelector(
    '.filters-toolbar__action-thematiques-filter--show-all'
  );
  showAllPostsButton.checked = false;

  const activeFilters = document.querySelectorAll(
    '.filters-toolbar__action-thematiques-filter:checked'
  );
  if (activeFilters.length === 0) {
    const showAllCheckbox = document.querySelector(
      '.filters-toolbar__action-thematiques-filter--show-all'
    );
    showAllCheckbox.checked = true;
    return showAllPosts();
  }

  const posts = Array.from(activeFilters).map((filter) => filter.getAttribute('value'));
  hydrateFilteredQuestions(posts);

  const loadAllButton = document.querySelector('.filters-toolbar__action-button--load-all');
  loadAllButton.removeAttribute('hidden');

  const resetAllButton = document.querySelector('.filters-toolbar__action-button--reset-filter');
  resetAllButton.removeAttribute('hidden');

  updateActiveFiltersViewer();

  // Set Toolbar Filter-Active Status

  const filtersToolbar = document.querySelector('.filters-toolbar--faq');
  filtersToolbar.setAttribute('filter-active', '');
}

// ###########################
// ### HYDRATATION
// ###########################

async function hydrateFilteredQuestions(questionsIds) {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const faqRowsContainer = document.querySelector('.post-question-page__accordeons-container');
  faqRowsContainer.setAttribute('isLoading', 'true');

  const response = await fetch(
    `/wp-json/homegrade-datas/v1/build/faq-details-rows?current-page-language=${currentLanguage}&questions-ids=${questionsIds}`
  );
  faqDatas = await response.json();

  faqRowsContainer.innerHTML = faqDatas.html_template;
  const postFounds = await faqDatas.total_posts_found;
  updatePostCountResults(postFounds);
  faqRowsContainer.removeAttribute('isLoading');
}
async function hydrateAllQuestions(CurrentMainParentThematiqueId) {
  const currentLanguage = document.querySelector('body').getAttribute('current-language');
  const faqRowsContainer = document.querySelector('.post-question-page__accordeons-container');

  faqRowsContainer.setAttribute('isLoading', 'true');

  const response = await fetch(
    `/wp-json/homegrade-datas/v1/build/faq-details-rows-all?current-page-language=${currentLanguage}&parent-thematique-id=${CurrentMainParentThematiqueId}`
  );
  faqDatas = await response.json();

  faqRowsContainer.innerHTML = faqDatas.html_template;

  updatePostCountResults(faqDatas.total_posts_found);
  faqRowsContainer.removeAttribute('isLoading');
}

// ###########################
// ### INSTATIATE
// ###########################

export default async function taxonomyThematiqueFaqInit() {
  const faqFiltersToolbar = document.querySelector('.filters-toolbar--faq');
  if (!faqFiltersToolbar) return;
  handleDeployCloseAllDetails();
  handleFilterPosts();
  handleSubmenuToggle();
}
