/* eslint-disable no-return-assign */
import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';

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

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

const Accordion = ({ module, openAll = false, openItem, closeOthers = false }) => {
  const { items } = module;
  const itemRefs = useRef([]);
  const btnRefs = useRef([]);

  const openAllItems = () => {
    for (let i = 0; i < itemRefs.current.length; i += 1) {
      itemRefs.current[i].classList.add(styles.active);
      btnRefs.current[i].classList.add(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 (openAll) {
      openAllItems();
    }
  }, [openAll]);
  useEffect(() => {
    if (openItem) {
      openSingleItem(openItem - 1);
    }
  }, [openItem]);

  return (
    <>
      <div className={styles.accordionContainer || ''}>
        {items.map((item, index) => (
          <div key={keygen()} className={styles.accordionItem || ''}>
            <button
              onClick={() => toggle(index)}
              className={`${styles.title || ''} accordion-gtm btn-cta`}
              type="button"
              ref={(el) => (btnRefs.current[index] = el)}
            >
              <div dangerouslySetInnerHTML={{ __html: item.title }} />
            </button>
            <div className={styles.content || ''} ref={(el) => (itemRefs.current[index] = el)}>
              <div dangerouslySetInnerHTML={{ __html: item.content }} />
            </div>
          </div>
        ))}
      </div>
    </>
  );
};

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

export default Accordion;
