import { useFilterContext } from '../FilterContext';
import { useCollectionContext } from '../CollectionContext';
import { useEffect, useState } from 'react';
import { FilterValueTotalState } from '../../state';
import { CollectionOptimisticActions, FiltersMap } from '@wix/bex-core';

export interface UseFilterValueTotalStateParams<V, T, F extends FiltersMap> {
  /**
   * The filter value (passed at first argument to `counterBadge(value)`)
   */
  readonly value: V | null | undefined;
  /**
   * [`OptimisticActions`](./?path=/story/features-actions-updates--collectionoptimisticactions) instance to wire the total to
   */
  readonly optimisticActions?: CollectionOptimisticActions<T, F>;
  /**
   * When set to `true` the total value will not change after table search
   */
  readonly ignoreSearch?: boolean;
}

export function useFilterValueTotalState<V, T, F extends FiltersMap>({
  value,
  ...params
}: UseFilterValueTotalStateParams<V, T, F>) {
  const filter = useFilterContext<V[]>();
  const collection = useCollectionContext();

  const [state] = useState(
    () =>
      new FilterValueTotalState({
        filter,
        value,
        collection,
        ...params,
      }),
  );

  useEffect(() => state.init(), []);
  useEffect(() => {
    if (value !== state.value) {
      state.refresh(value);
    }
  }, [value]);

  return state;
}
