import { Filter, FiltersMap } from '@wix/bex-core';
import { ReactElement, useEffect, useState } from 'react';
import { useFilterRenderingContext } from '../FilterRenderingContext';
import { CollectionFilterState } from './CollectionFilterState';
import { CollectionToolbarFiltersState } from '../CollectionToolbarFilters/CollectionToolbarFiltersState';

export interface CollectionFilterProps<T, F extends FiltersMap, V> {
  readonly filter: Filter<V>;
  readonly state: CollectionToolbarFiltersState<T, F>;
  readonly children: ReactElement;
}

export function CollectionFilter<T, F extends FiltersMap, V>(
  props: CollectionFilterProps<T, F, V>,
) {
  const { filter, children, state: toolbarFiltersState } = props;

  const { location } = useFilterRenderingContext();

  const [state] = useState(
    () =>
      new CollectionFilterState({
        filter,
        toolbarFiltersState,
        location,
      }),
  );

  useEffect(() => state.init(), []);

  return children;
}
