import React, { FunctionComponent } from 'react';

import { TabBarProps } from './types.d';
import { Grid, GridRow, GridColumn } from '../Grid';
import { Tab } from './tab';
import { StyledTabs, StyledTabPane } from './styled-components';
import { useTheme } from '../Theme';

const Page: FunctionComponent<{ children?: React.ReactElement | Array<React.ReactElement> }> = ({ children }) => (
  <Grid className="tab-bar-page">
    <GridRow>
      <GridColumn col={12}>{children}</GridColumn>
    </GridRow>
  </Grid>
);

export const TabBar: FunctionComponent<TabBarProps> = ({
  activeKey = '',
  className = '',
  defaultActiveKey,
  extraContent,
  hideBottomDivider = false,
  onChange,
  onClose,
  onTabClick = () => {},
  style,
  tabBarPosition,
  tabs,
}): React.ReactElement => {
  const theme = useTheme();
  return (
    <StyledTabs
      $hideBottomDivider={hideBottomDivider}
      $theme={theme}
      activeKey={activeKey}
      className={className}
      defaultActiveKey={defaultActiveKey || tabs.length > 0 ? tabs[0].id : undefined}
      onChange={onChange}
      onTabClick={onTabClick}
      style={style}
      tabBarExtraContent={extraContent}
      tabPosition={tabBarPosition}
    >
      {tabs.map((tab) => (
        <StyledTabPane
          $theme={theme}
          disabled={tab.disabled}
          tab={
            <Tab
              customComponent={tab.customComponent}
              disabled={tab.disabled}
              editable={tab.editable}
              hideCloseButton={tab.hideCloseButton}
              id={tab.id}
              isActive={activeKey === tab.id}
              name={tab.name}
              onChangeTab={tab.onChangeTab}
              onClose={onClose}
              tooltip={tab.tooltip}
            />
          }
          key={`${tab.id}`}
        >
          {tab.withPage ? <Page>{tab.component}</Page> : tab.component}
        </StyledTabPane>
      ))}
    </StyledTabs>
  );
};
