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

import { createContextSelector } from '../utils/react';

export interface ChipGroupContextValues {
  checkSelected?: (value: string) => boolean;
  onSelect: (value: string, state: boolean) => void;
  multiple?: boolean;
}

export interface ChipGroupProviderProps {
  selected: string[];
  onSelect?: (value: string[]) => void;
  children: React.ReactNode;
  multiple: boolean;
}

const [ChipGroupContext, useChipGroupContext] =
  createContextSelector<ChipGroupContextValues>({
    onSelect: () => {},
  });

export const ChipGroupProvider = ({
  selected,
  onSelect,
  multiple,
  children,
}: ChipGroupProviderProps) => {
  const isSelected = useCallback(
    (value: string) => selected.includes(value),
    [selected],
  );

  const getNewSelected = useCallback(
    (value: string, state: boolean) => {
      if (!onSelect) {
        return;
      }

      if (state) {
        onSelect([value, ...selected]);
      } else {
        onSelect(selected.filter(id => id !== value));
      }
    },
    [selected, onSelect],
  );

  const contextValue = useMemo(
    () => ({ checkSelected: isSelected, onSelect: getNewSelected, multiple }),
    [isSelected, getNewSelected, multiple],
  );

  return (
    <ChipGroupContext.Provider value={contextValue}>
      {children}
    </ChipGroupContext.Provider>
  );
};

export { useChipGroupContext };
