/* eslint-disable react/forbid-prop-types */
/* eslint-disable react/jsx-no-bind */
/* eslint-disable import/no-extraneous-dependencies */
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import Tab from 'gatsby-core-theme/src/hooks/tabs/tab/tab';
import styles from './tab-list.module.scss';
import keygen from '~helpers/keygen';
import { closeOtherSelects } from '~helpers/select';

const TabList = ({
  items,
  onClick,
  activeTab,
  activeTabClass = '',
  showAll,
  alignRight = false,
  gtmClass = '',
  showIcon = false,
  icon = null,
  showNumberOfResults = false,
  totalResults,
}) => {
  const filterBtn = useRef(null);
  const tabList = useRef(null);

  const tabItems = showAll
    ? [
        <div results={totalResults} label={showAll} tabId={`${showAll}_0`} key={keygen()} />,
        ...items,
      ]
    : items;

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

  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((item, index) => {
          if (item === null) return null;
          const { label, results } = item.props;
          return (
            <Tab
              activeTab={activeTab}
              activeTabClass={activeTabClass}
              key={keygen()}
              tabId={`${label}_${index}`}
              label={label}
              onClick={onClick}
              toggleDropdown={showDropdown}
              gtmClass={gtmClass}
              showIcon={showIcon}
              icon={icon}
              showResults={showNumberOfResults}
              results={results}
            />
          );
        })}
      </ol>
    </div>
  );
};

TabList.propTypes = {
  items: PropTypes.arrayOf(PropTypes.any).isRequired,
  showAll: PropTypes.string,
  onClick: PropTypes.func,
  activeTab: PropTypes.string,
  activeTabClass: PropTypes.string,
  alignRight: PropTypes.bool,
  gtmClass: PropTypes.string,
  showIcon: PropTypes.string,
  icon: PropTypes.func,
  showNumberOfResults: PropTypes.bool,
  totalResults: PropTypes.number,
};

export default TabList;
