import { useCallback, useMemo } from 'react';
import { useStore } from '../services/store';
import { IMedia } from '../types';

interface UseCarouselThumbnailVideoLoadingResult {
  isCarouselThumbnailVideoEnabled: boolean;
  shouldLoadCarouselVideo: boolean;
  handleCarouselVideoReady: () => void;
}

const useCarouselThumbnailVideoLoading = (
  media: IMedia,
): UseCarouselThumbnailVideoLoadingResult => {
  const store = useStore();
  const { type: widgetLayout, shop_this_look_display: shopThisLookDisplay } = store.data.settings;
  const medias = store.data.content.medias;
  const isCarouselThumbnailVideoEnabled =
    widgetLayout === 'carousel' && (shopThisLookDisplay === 'product_list' || store.isMobile);

  const currentCarouselMedia = useMemo(() => {
    if (!isCarouselThumbnailVideoEnabled || medias.length === 0) {
      return null;
    }

    const normalizedPosition =
      ((store.currentPosition % medias.length) + medias.length) % medias.length;

    return medias[normalizedPosition] ?? null;
  }, [isCarouselThumbnailVideoEnabled, medias, store.currentPosition]);

  const previousCarouselMedia = useMemo(() => {
    if (!currentCarouselMedia || medias.length <= 1) {
      return null;
    }

    const previousIndex =
      ((currentCarouselMedia.postIndex - 1) % medias.length + medias.length) % medias.length;

    return medias[previousIndex] ?? null;
  }, [currentCarouselMedia, medias]);

  const nextCarouselMedia = useMemo(() => {
    if (!currentCarouselMedia || medias.length <= 1) {
      return null;
    }

    return medias[(currentCarouselMedia.postIndex + 1) % medias.length] ?? null;
  }, [currentCarouselMedia, medias]);

  const activeCarouselPostId = currentCarouselMedia?.id ?? null;
  const isActiveCarouselVideo = activeCarouselPostId === media.id;
  const isShoulderCarouselVideo =
    media.id === previousCarouselMedia?.id || media.id === nextCarouselMedia?.id;
  const shouldLoadCarouselVideo =
    isCarouselThumbnailVideoEnabled &&
    (isActiveCarouselVideo ||
      (isShoulderCarouselVideo &&
        store.unlockedShouldersForCarouselPostId === activeCarouselPostId));

  const handleCarouselVideoReady = useCallback(() => {
    if (
      !isCarouselThumbnailVideoEnabled ||
      !activeCarouselPostId ||
      media.id !== activeCarouselPostId ||
      store.unlockedShouldersForCarouselPostId === activeCarouselPostId
    ) {
      return;
    }

    store.setStoreState((state) => {
      if (state.unlockedShouldersForCarouselPostId === activeCarouselPostId) {
        return state;
      }

      return {
        ...state,
        unlockedShouldersForCarouselPostId: activeCarouselPostId,
      };
    });
  }, [
    activeCarouselPostId,
    isCarouselThumbnailVideoEnabled,
    media.id,
    store,
  ]);

  return {
    isCarouselThumbnailVideoEnabled,
    shouldLoadCarouselVideo,
    handleCarouselVideoReady,
  };
};

export default useCarouselThumbnailVideoLoading;