import React from 'react';

import Tooltip from '@mui/material/Tooltip';
import TabUnstyled from '@mui/base/TabUnstyled';
import TabsUnstyled from '@mui/base/TabsUnstyled';

import { bem } from 'utils/bem';
import { Typography, TYPOGRAPHY_TYPE } from 'components/Typography';

import { THEME } from '../../constants'; // TODO: finish config Rollup to work properly with absolute path
import { ITabData, ITabsProps } from './types';
import { isGenericType } from './helpers';

import tabsStyles from './tabs.scss';

const tabsClassNames = bem(tabsStyles, 'tabs');

export const Tabs = <T extends string | number>({
  theme = THEME.light,
  tabsData,
  value,
  onChange,
  className,
  dataAttributes,
}: ITabsProps<T>): JSX.Element => {
  const handleChange = (event: React.SyntheticEvent, newValue: string | number | boolean): void => {
    if (isGenericType<T>(newValue)) {
      onChange(newValue);
    }
  };

  return (
    <TabsUnstyled
      {...dataAttributes}
      className={tabsClassNames('', { [theme]: true }, className)}
      value={value}
      onChange={handleChange}
    >
      {tabsData.map((tab: ITabData<T>) => (
        <TabUnstyled
          key={tab.value}
          value={tab.value}
          disabled={tab.disabled}
        >
          <Tooltip {...(tab.tooltip ?? { title: null })}>
            <div className="tab-content">
              {tab.leftElement && tab.leftElement}
              <Typography
                type={TYPOGRAPHY_TYPE.subtitle3}
                theme={theme}
              >
                {tab.label}
              </Typography>
              {tab.rightElement && tab.rightElement}
            </div>
          </Tooltip>
        </TabUnstyled>
      ))}
    </TabsUnstyled>
  );
};
