import * as Ariakit from '@ariakit/react';
import { getClassNames } from '@websolutespa/bom-core';
import { IconX } from '@websolutespa/bom-mixer-icons';
import { forwardRef, HTMLProps, useContext } from 'react';
import styled from 'styled-components';
import { getVariantKey } from '../../variants';
import { SelectContext } from './select.context';
import { ISelectVariants, selectVariants } from './select.variants';

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

export type SelectValueProps = HTMLProps<HTMLDivElement> & {
  value?: string | string[];
  label?: string;
  variant?: keyof typeof selectVariants | (string & {});
  variants?: ISelectVariants;
};

export const SelectValue = forwardRef<HTMLDivElement, SelectValueProps>(
  function SelectValue({
    value,
    label,
    variant,
    variants,
    className,
    ...props
  }: SelectValueProps, ref) {
    const selectContext = Ariakit.useSelectContext();
    const context = useContext(SelectContext);
    if (!selectContext) {
      return;
    }
    if (!context) {
      return;
    }
    const onRemove = () => {
      const state = selectContext?.getState();
      const stateValue = (Array.isArray(state.value) ? state.value : []).filter(x => x !== value);
      selectContext.setValue([...stateValue]);
      // console.log(value, selectContext);
    };
    const classNames = getClassNames('select__value', className);
    return (
      <SelectValueStyle
        ref={ref}
        className={classNames}
        variant={context.variant}
        variants={context.variants}
        role="option"
        aria-selected
        aria-label={label}
        {...props as any}
        onClick={() => onRemove()}
      >
        {label} <IconX />
      </SelectValueStyle>
    );
  });
