import { useCallback, useEffect, useMemo, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { fetchClip } from '@/hooks/useClip';
import { Clip } from '@/state/clipStore';

export const useClips = (clipIds: string[]) => {
  const { clips: clipsStore } = useStores();
  const [clipsById, setClipsById] = useState<Record<string, Clip>>({});

  const refetch = useCallback(
    async (id: string) => {
      await fetchClip(clipsStore, id, true, false, (clip) => {
        setClipsById((prev) => ({ ...prev, [id]: clip }));
      });
    },
    [clipsStore]
  );

  useEffect(() => {
    clipIds.forEach(refetch);
  }, [clipIds, refetch]);

  return useMemo(
    () => ({
      clips: clipsById,
    }),
    [clipsById]
  );
};
