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 { isEmptyValue } from '../utils/utils';
import { SelectValue } from './select-value';
import { SelectContext } from './select.context';
import { ISelectVariants, selectVariants } from './select.variants';

const SelectSelectStyle = styled(Ariakit.Select) <SelectSelectProps>`
  ${props => getVariantKey('select', props.variant, props.variants)}
`;

export type SelectSelectProps = Ariakit.SelectProps & {
  variant?: keyof typeof selectVariants | (string & {});
  variants?: ISelectVariants;
  before?: ReactNode;
  after?: ReactNode;
};

export const SelectSelect = forwardRef<HTMLButtonElement, SelectSelectProps>(
  function SelectSelect({
    children,
    variant,
    variants,
    before,
    after,
    className,
    ...props
  }: SelectSelectProps, ref) {
    const context = useContext(SelectContext);
    const store = Ariakit.useSelectContext();
    const value = Ariakit.useStoreState(store, 'value');
    if (!context) {
      return;
    }
    const classNames = getClassNames('select__select', { empty: isEmptyValue(value) }, className);
    return (
      <SelectSelectStyle
        ref={ref}
        className={classNames}
        id={context.name}
        name={context.name}
        variant={context.variant}
        variants={context.variants}
        onFocus={context.onFocus}
        onBlur={context.onBlur}
        {...props}
      >
        {before}
        <div className="select__selection">
          <SelectSelection />
        </div>
        {after}
        <Ariakit.SelectArrow>{children}</Ariakit.SelectArrow>
      </SelectSelectStyle>
    );
  });

export function SelectSelection() {
  const selectContext = Ariakit.useSelectContext();
  const context = useContext(SelectContext);
  if (!context) {
    return;
  }
  const state = selectContext?.getState();
  const items = context.options ?
    context.options.map(x => ({
      value: String(x.id),
      label: x.name,
    })) :
    (state?.items || [])
      .filter(x => x.element!.parentElement !== state?.anchorElement)
      .map((x) => ({
        value: x.value,
        label: x.element!.innerText || x.value,
      })) as { value: string, label: string }[];
  const value = state?.value;
  if (context.multiple && Array.isArray(value)) {
    const options = items.filter(x => value.indexOf(x.value) !== -1);
    if (options.length > 0) {
      return (
        <div className="select__values">
          {options.map((option) => (
            <SelectValue key={option.value} value={option.value} label={option.label} />
          ))}
        </div>
      );
    } else {
      return context.placeholder || 'Select';
    }
  }
  // console.log(context.options, state?.items, items, value);
  return items.find(x => x.value === value)?.label || context.placeholder || 'Select';
}
