import * as Ariakit from '@ariakit/react';
import { getClassNames } from '@websolutespa/bom-core';
import { forwardRef, ReactNode, useContext } from 'react';
import styled from 'styled-components';
import { getVariantKey } from '../../variants';
import { Role } from '../role/role';
import { UIStyledComponentProps } from '../types';
import { getCssResponsive } from '../utils';
import { TabsContext } from './tabs.context';
import { ITabsVariants, tabsVariants } from './tabs.variants';

const TabsTitleStyle = styled(Ariakit.Tab) <TabsTitleProps>`
  ${props => getVariantKey('title', props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

export type TabsTitleProps = Ariakit.TabProps & UIStyledComponentProps<{
  className?: string;
  variant?: keyof typeof tabsVariants | (string & {});
  variants?: ITabsVariants;
  children?: ReactNode;
  asChild?: boolean;
}>;

export const TabsTitle = forwardRef<HTMLButtonElement, TabsTitleProps>(
  function TabsTitle({
    asChild,
    className,
    variant,
    variants,
    children,
    ...props
  }, ref) {
    const classNames = getClassNames('tabs__title', className);
    const context = useContext(TabsContext);
    return (
      <TabsTitleStyle
        className={classNames}
        variant={variant || context.variant}
        variants={variants || context.variants}
        ref={ref}
        {...props}
        render={asChild ? (
          <Role />
        ) : (
          undefined
        )}
      >{children}</TabsTitleStyle>
    );
  }
);
