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

const ComboboxValueStyle = styled.div<ComboboxValueProps>`
  ${props => getVariantKey('value', props.variant, props.variants)}
`;

export type ComboboxValueProps = HTMLProps<HTMLDivElement> & {
  value?: string | string[];
  label?: string;
  variant?: keyof typeof comboboxVariants | (string & {});
  variants?: IComboboxVariants;
  children?: ReactNode;
};

export const ComboboxValue = forwardRef<HTMLDivElement, ComboboxValueProps>(
  function ComboboxValue({
    value,
    label,
    variant,
    variants,
    className,
    children,
    ...props
  }: ComboboxValueProps, ref) {
    const comboboxContext = Ariakit.useComboboxContext();
    const context = useContext(ComboboxContext);
    if (!comboboxContext) {
      return;
    }
    if (!context) {
      return;
    }
    const onRemove = () => {
      const state = comboboxContext?.getState();
      const stateSelectedValue = (Array.isArray(state.selectedValue) ? state.selectedValue : []).filter(x => x !== value);
      comboboxContext.setSelectedValue([...stateSelectedValue]);
      // console.log(value, comboboxContext);
    };
    const classNames = getClassNames('combobox__value', className);
    return (
      <ComboboxValueStyle
        ref={ref}
        className={classNames}
        variant={context.variant}
        variants={context.variants}
        role="option"
        aria-selected
        aria-label={label}
        {...props as any}
        onClick={() => onRemove()}
      >
        {label} <IconX />
      </ComboboxValueStyle>
    );
  });
