import { useApi } from "@/api";
import metricService, { EGoals, EMetrics } from "@/services/metric/metricService";
import { actions, selectors } from "@/store";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";


export const usePersonalVideo = () => {
    const api = useApi();
    const dispatch = useDispatch();
    const token = useSelector(selectors.selectToken);
    const { generatingVideo, videoId, createdDate } = useSelector(
        selectors.selectPersonalVideo
    );

    const personalVideoTimeLimit = useMemo(() => import.meta.env.AURA_PERSONAL_VIDEO_TIME_LIMIT, [])

    const requestVideoInterval = useRef<NodeJS.Timeout>();
    const [isVideoReady, setIsVideoReady] = useState(false);

    const clearPersonalVideoInterval = useCallback(() => {
        if (!requestVideoInterval.current) return;
        if (isVideoReady) return clearInterval(requestVideoInterval.current);
    }, [isVideoReady])

    const getTargetUserVideo = useCallback(async () => {
        const videos = await api.getUserVideos({
            token,
        });
        return videos.find((video) => video.id === videoId);
    }, [api, token, videoId]);

    useEffect(() => {
        clearPersonalVideoInterval();
        return () => {
            clearPersonalVideoInterval();
        };
    }, [clearPersonalVideoInterval])

    useEffect(() => {
        if (!generatingVideo) return setIsVideoReady(true);

        requestVideoInterval.current = setInterval(async () => {
            const video = await getTargetUserVideo();
            if (!video) return setIsVideoReady(true);
            if (video.videoUrl.length) {
                metricService.reachGoal(EGoals.ROSE_VIDEO_CREATED, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
                dispatch(actions.personalVideo.updateUrl(video.videoUrl));
                return setIsVideoReady(true);
            }
            if (new Date().getTime() - createdDate > Number(personalVideoTimeLimit) * 1000) {
                return setIsVideoReady(true);
            }
        }, 5000);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return useMemo(() => ({ isVideoReady }), [isVideoReady])
}