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

const TabsGroupStyle = styled.div<TabsGroupProps>`
  ${props => getVariantKey('group', props.variant, props.variants)}
  ${props => getCssResponsive(props)}
`;

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

export const TabsGroup = forwardRef<HTMLDivElement, React.PropsWithChildren<TabsGroupProps>>(
  function TabsGroup({
    tabs = true,
    className,
    variant,
    variants,
    children,
    combobox,
    composite,
    defaultActiveId,
    activeId,
    setActiveId,
    defaultItems,
    items,
    setItems,
    defaultSelectedId,
    selectedId,
    setSelectedId,
    focusLoop,
    focusShift,
    focusWrap,
    orientation,
    rtl,
    selectOnMove,
    virtualFocus,
    ...props
  }, ref) {
    const globalVariants = useVariants('tabs', tabsVariants);
    variant = variant || 'default';
    variants = variants || globalVariants;
    const classNames = getClassNames('tabs__group', className);
    return (
      <TabsProvider value={{
        variant,
        variants,
      }}>
        <Ariakit.TabProvider
          combobox={combobox}
          composite={composite}
          defaultActiveId={defaultActiveId}
          activeId={activeId}
          setActiveId={setActiveId}
          defaultItems={defaultItems}
          items={items}
          setItems={setItems}
          defaultSelectedId={defaultSelectedId}
          setSelectedId={setSelectedId}
          selectedId={selectedId}
          focusLoop={focusLoop}
          focusShift={focusShift}
          focusWrap={focusWrap}
          orientation={orientation}
          rtl={rtl}
          selectOnMove={selectOnMove}
          virtualFocus={virtualFocus}
        >
          <TabsGroupStyle
            className={classNames}
            variant={variant}
            variants={variants}
            ref={ref}
            {...props}
          >
            {children}
          </TabsGroupStyle>
        </Ariakit.TabProvider>
      </TabsProvider>
    );
  });

TabsGroup.displayName = 'TabsGroup';
