'use client';

import * as React from 'react';

import { useSelection } from '@/hooks/use-selection';
import type { Selection } from '@/hooks/use-selection';

import type { Vocabulary } from './type';

function noop(): void {
  return undefined;
}

export interface VocabulariesSelectionContextValue extends Selection {}

export const VocabulariesSelectionContext = React.createContext<VocabulariesSelectionContextValue>({
  deselectAll: noop,
  deselectOne: noop,
  selectAll: noop,
  selectOne: noop,
  selected: new Set(),
  selectedAny: false,
  selectedAll: false,
});

interface VocabulariesSelectionProviderProps {
  children: React.ReactNode;
  lessonCategories: Vocabulary[];
}

export function VocabulariesSelectionProvider({
  children,
  lessonCategories = [],
}: VocabulariesSelectionProviderProps): React.JSX.Element {
  const customerIds = React.useMemo(() => lessonCategories.map((customer) => customer.id), [lessonCategories]);
  const selection = useSelection(customerIds);

  return (
    <VocabulariesSelectionContext.Provider value={{ ...selection }}>{children}</VocabulariesSelectionContext.Provider>
  );
}

export function useVocabulariesSelection(): VocabulariesSelectionContextValue {
  return React.useContext(VocabulariesSelectionContext);
}
