import React, { useCallback, useMemo } from 'react';
import { clsx } from 'clsx';

import { forwardRef } from '../utils/react';
import { Box } from '../box';
import { AsProps } from '../types';
import { ChipGroupProvider } from './chip-group.context';
import * as css from './chip-group.css';

type ChipGroupSingleProps = {
  multiple?: false;
  selected?: string;
  onSelect?: (selected?: string) => void;
};

type ChipGroupMultiProps = {
  multiple: true;
  selected?: string[];
  onSelect?: (selected: string[]) => void;
};

export type ChipGroupProps = (ChipGroupSingleProps | ChipGroupMultiProps) & {};

export const ChipGroup = forwardRef<
  'div',
  ChipGroupProps,
  ChipGroupProps & AsProps<'div'>
>(function ChipGroup(
  {
    as = 'div',
    className,
    multiple: userMultiple,
    selected,
    onSelect: userOnSelect,
    children,
    ...rest
  },
  ref,
) {
  const multiple = !!userMultiple;

  const selectedValues = useMemo(() => {
    if (!selected) {
      return [];
    }

    return Array.isArray(selected) ? selected : [selected];
  }, [selected]);

  const onSelect = useCallback(
    (nextSelected: string[]) => {
      if (!userOnSelect) {
        return;
      }

      userMultiple ? userOnSelect(nextSelected) : userOnSelect(nextSelected[0]);
    },
    [userMultiple, userOnSelect],
  );

  return (
    <ChipGroupProvider
      selected={selectedValues}
      onSelect={onSelect}
      multiple={multiple}
    >
      <Box {...rest} as={as} ref={ref} className={clsx(className, css.group)}>
        {children}
      </Box>
    </ChipGroupProvider>
  );
});
