import React, { useState } from 'react';
import PropTypes from 'prop-types';
import loadable from '@loadable/component';
import styles from './tabs.module.scss';

const Tabs = ({
  children,
  showAll,
  tabsAlign,
  activeTabClass = '',
  HeaderComp,
  headerClass = '',
  gtmClass = '',
}) => {
  const showAllTabId = `${showAll}_0`;
  const [activeTab, setActiveTab] = useState(
    showAll ? showAllTabId : `${children[0].props.label}_0`
  );
  const showTabs = children.length > 1;
  const TabList = showTabs && loadable(() => import('./tab/tab-list'));
  const tabHeaderClass = `${styles.tabsHeader || ''} ${!HeaderComp ? styles.tabsOnly || '' : ''} ${
    styles[headerClass] || ''
  } ${tabsAlign === 'right' ? styles.invertOrder : ''}`;

  return (
    <>
      <div className={tabHeaderClass || ''}>
        {TabList && (
          <TabList
            onClick={(tabId) => {
              setActiveTab(tabId);
            }}
            items={children}
            activeTab={activeTab}
            activeTabClass={activeTabClass}
            showAll={showAll}
            gtmClass={gtmClass}
            alignRight={tabsAlign === 'right'}
          />
        )}
        {HeaderComp && <div className={styles.headerComp || ''}>{HeaderComp}</div>}
      </div>
      <div className="tab-content">
        {children.map(
          (child, index) =>
            child !== null &&
            (`${child.props.label}_${showAll ? index + 1 : index}` === activeTab ||
              activeTab === showAllTabId) &&
            child.props.children
        )}
      </div>
    </>
  );
};

Tabs.defaultProps = {
  showAll: null,
};

Tabs.propTypes = {
  children: PropTypes.arrayOf(PropTypes.any).isRequired,
  showAll: PropTypes.string,
  tabsAlign: PropTypes.string,
  activeTabClass: PropTypes.string,
  HeaderComp: PropTypes.objectOf(PropTypes.any),
  headerClass: PropTypes.string,
  gtmClass: PropTypes.string,
};

export default Tabs;
