/* eslint-disable jsx-a11y/click-events-have-key-events */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable no-return-assign */
import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';

import styles from './faq.module.scss';
import keygen from '~helpers/keygen';

/* eslint-disable react/no-danger */

const Faq = ({ module, closeAll = false, openItem, closeOthers = false, icon = '' }) => {
  const { items } = module;
  const itemRefs = useRef([]);
  const btnRefs = useRef([]);

  const closeAllItems = () => {
    for (let i = 0; i < itemRefs.current.length; i += 1) {
      itemRefs.current[i].classList.remove(styles.active);
      btnRefs.current[i].classList.remove(styles.invertArrow);
    }
  };

  const openSingleItem = (index) => {
    if (itemRefs.current[index]) {
      itemRefs.current[index].classList.add(styles.active);
      btnRefs.current[index].classList.add(styles.invertArrow);
    }
  };

  const closeOtherItems = (index) => {
    for (let i = 0; i < itemRefs.current.length; i += 1) {
      if (i !== index) {
        itemRefs.current[i].classList.remove(styles.active);
        btnRefs.current[i].classList.remove(styles.invertArrow);
      }
    }
  };

  // toggle open/close an item
  const toggle = (index) => {
    btnRefs.current[index].classList.toggle(styles.invertArrow);
    itemRefs.current[index].classList.toggle(styles.active);
    if (closeOthers) {
      closeOtherItems(index);
    }
  };

  useEffect(() => {
    if (closeAll) {
      closeAllItems();
    }
  });
  useEffect(() => {
    if (openItem) {
      openSingleItem(openItem - 1);
    }
  });

  return (
    <>
      <div className={styles?.faqContainer || ''}>
        {items.map((item, index) => (
          <div key={keygen()} className={styles?.faqItem || ''}>
            <div
              onClick={() => toggle(index)}
              className={`${styles?.title || ''} faq-gtm`}
              ref={(el) => (btnRefs.current[index] = el)}
            >
              {icon && <span className={styles?.circle || ''}>{icon} </span>}
              <div dangerouslySetInnerHTML={{ __html: item.question }} />
            </div>
            <div
              className={`${styles?.content || ''} ${styles?.active || ''}`}
              ref={(el) => (itemRefs.current[index] = el)}
              dangerouslySetInnerHTML={{ __html: item.answer }}
            />
          </div>
        ))}
      </div>
    </>
  );
};

Faq.propTypes = {
  module: PropTypes.shape({
    anchor_label: PropTypes.string,
    items: PropTypes.arrayOf(
      PropTypes.shape({
        title: PropTypes.string,
        content: PropTypes.string,
      })
    ),
  }).isRequired,
  closeAll: PropTypes.bool,
  openItem: PropTypes.number,
  closeOthers: PropTypes.bool,
  styles: PropTypes.shape({}),
  icon: PropTypes.func,
};

export default Faq;
