import * as Ariakit from '@ariakit/react';
import { getClassNames } from '@websolutespa/bom-core';
import { forwardRef, useContext } from 'react';
import styled from 'styled-components';
import { getVariantKey } from '../../variants';
import { ComboboxContext } from './combobox.context';
import { comboboxVariants, IComboboxVariants } from './combobox.variants';

const ComboboxOptionStyle = styled(Ariakit.ComboboxItem) <ComboboxOptionProps>`
  ${props => getVariantKey('option', props.variant, props.variants)}
`;

export type ComboboxOptionProps = Ariakit.ComboboxItemProps & {
  variant?: keyof typeof comboboxVariants | (string & {});
  variants?: IComboboxVariants;
};

export const ComboboxOption = forwardRef<HTMLDivElement, ComboboxOptionProps>(
  function ComboboxOption({
    variant,
    variants,
    className,
    ...props
  }: ComboboxOptionProps, ref) {
    const context = useContext(ComboboxContext);
    if (!context) {
      return;
    }
    const classNames = getClassNames('combobox__option', className);
    return (
      <ComboboxOptionStyle
        ref={ref}
        className={classNames}
        variant={variant || context.variant}
        variants={variants || context.variants}
        {...props}
      />
    );
  });
