import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';

import Tab from './tab';
import styles from './tab-list.module.scss';
import keygen from '~helpers/keygen';
import useWindowSize from '~hooks/useWindowSize';
import { closeOtherSelects } from '~helpers/select';

/* eslint no-shadow: ["error", { "allow": ["items"] }] */

const TabList = ({
  items,
  onClick,
  activeTab,
  activeTabClass = '',
  showAll,
  alignRight = false,
  gtmClass = '',
  showNumberOfResults = false,
  totalResults,
}) => {
  const [tabItems, setTabItems] = useState(items);

  const filterBtn = useRef(null);
  const tabList = useRef(null);

  useEffect(() => {
    if (showAll) {
      // eslint-disable-next-line react/no-unknown-property
      setTabItems([
        <div results={totalResults} label={showAll} tabId={`${showAll}_0`} key={keygen()} />,
        ...items,
      ]);
    }
  }, [showAll, items]);

  function showDropdown() {
    closeOtherSelects(tabList.current);
    tabList.current.classList.toggle(styles.show);
    filterBtn.current.classList.toggle(styles.flip);
  }

  const [width] = useWindowSize();
  const isMobile = width < 992;

  return (
    <div className={`${styles.tabList || ''} ${alignRight && (styles.right || '')}`}>
      <button
        ref={filterBtn}
        className={`${styles.select || ''} ${gtmClass || ''} btn-cta`}
        type="button"
        onClick={showDropdown}
        data-id="select-button"
      >
        {activeTab.split('_')[0]}
      </button>
      <ol ref={tabList} className={styles.list || ''} data-id="select-list">
        {tabItems.map((items, index) => {
          if (items === null) return null;
          const { label, results } = items.props;
          if (isMobile && label === activeTab.split('_')[0]) return null;
          return (
            <Tab
              activeTab={activeTab}
              activeTabClass={activeTabClass}
              key={keygen()}
              tabId={`${label}_${index}`}
              label={label}
              onClick={onClick}
              // eslint-disable-next-line react/jsx-no-bind
              toggleDropdown={showDropdown}
              gtmClass={gtmClass}
              showResults={showNumberOfResults}
              results={results}
            />
          );
        })}
      </ol>
    </div>
  );
};

TabList.propTypes = {
  // eslint-disable-next-line react/forbid-prop-types
  items: PropTypes.arrayOf(PropTypes.any).isRequired,
  showAll: PropTypes.string,
  onClick: PropTypes.func,
  activeTab: PropTypes.string,
  activeTabClass: PropTypes.string,
  alignRight: PropTypes.bool,
  gtmClass: PropTypes.string,
  showNumberOfResults: PropTypes.bool,
  totalResults: PropTypes.number,
};

export default TabList;
