import { useCallback } from 'react';

import { ICollectionComponentState } from '../state/ICollectionComponentState';
import { CollectionState } from '@wix/bex-core';
import { useSyncCollectionOnEntityReturn } from './useSyncCollectionOnEntityReturn';

export function useSyncCollectionOnEntityUpdate<
  T,
  S extends ICollectionComponentState,
>(
  cachedState?: S,
  getCollectionsToUpdate?: (state: S, entity: T) => CollectionState<T>[] | null,
) {
  const updateCollection = useCallback(
    (collection: CollectionState<T>, updatedEntity: T) => {
      collection.changeItem(updatedEntity);
    },
    [],
  );

  const checkIfViewSynced = useCallback(
    async (collection: CollectionState<T>, entity: T) => {
      const itemKey = collection.itemKey(entity);
      let fetchedPageInfo = null;
      for (
        let fetchIndex = collection.fetchesHistory.length - 1;
        fetchIndex >= 0;
        fetchIndex--
      ) {
        const fetch = collection.fetchesHistory[fetchIndex];
        if (
          fetch.itemsKeys.some((fetchedItemKey) => fetchedItemKey === itemKey)
        ) {
          fetchedPageInfo = fetch.queryPageInfo;
          break;
        }
      }

      if (!fetchedPageInfo) {
        console.error('Fetched page info for updated entity not found');
        return false;
      }

      const itemQuery = {
        ...collection.query.asComputed,
        ...fetchedPageInfo,
      };

      const currentIndex = collection.getKeyedItem(itemKey)?.indexWithinPage;

      const updatedData = await collection.fetchData(itemQuery);
      const newIndex = updatedData.items.findIndex(
        (item) => itemKey === collection.itemKey(item),
      );

      return newIndex === currentIndex;
    },
    [cachedState],
  );

  useSyncCollectionOnEntityReturn({
    cachedState,
    updateCollection,
    checkIfViewSynced,
    getEntityFromRouterState: (state: { _updatedEntity?: T }) =>
      state._updatedEntity,
    getCollectionsToUpdate,
  });
}
