"use client";

import { useEffect, useRef, useState } from "react";

import { fetchGenerationStatus } from "@/entities/generations/actions";
import { GenerationResponse } from "@/entities/generations/types";

export function useGenerationPolling(id: string, interval = 3000) {
  const [data, setData] = useState<GenerationResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const timeoutIdRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (!id) {
      setError("ID of generation not found.");
      setIsLoading(false);
      return;
    }

    const poll = async () => {
      if (!timeoutIdRef) return;

      const response = await fetchGenerationStatus(id);

      if (response.error) {
        setError(response.error);
        setIsLoading(false);
        return;
      }

      const status = response.data?.status;

      if (status === "done" || status === "failed") {
        setData(response.data);
        setIsLoading(false);
        return;
      }

      timeoutIdRef.current = setTimeout(poll, interval);
    };

    poll();

    return () => {
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current);
      }
    };
  }, [id, interval]);

  return { data, error, isLoading };
}
