import { CollectionState, FiltersMap } from '@wix/bex-core';
import { useEffect } from 'react';
import { useCollectionPageContext } from '../providers';
import { reaction, runInAction } from 'mobx';

export const useSyncTotal = <T, F extends FiltersMap>(
  state: CollectionState<T, F>,
) => {
  const pageState = useCollectionPageContext();

  useEffect(() => {
    if (state.totalStatus === 'success') {
      runInAction(() => {
        pageState.total = state.total;
      });
    }

    return reaction(
      () => ({
        status: state.totalStatus,
        total: state.total,
      }),
      ({ status, total }) => {
        pageState.total = status === 'success' ? total : false;
      },
    );
  }, []);
};
