import { useState, useEffect, useCallback, useRef } from 'react';
import { supabase } from '@/integrations/supabase/client';

export function usePublicFormReport(submissionId) {
  const [report, setReport] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  const retryCount = useRef(0);
  const maxRetries = 3;

  const fetchReport = useCallback(async () => {
    if (!submissionId) {
      setLoading(false);
      return;
    }
    
    setLoading(true);
    setError(null);
    
    try {
      const { data, error: fetchError } = await supabase
        .from('public_form_submission_reports')
        .select(`
          *,
          public_form_templates (
            title,
            description,
            settings
          )
        `)
        .eq('submission_id', submissionId)
        .maybeSingle();

      if (fetchError) {
        throw fetchError;
      }

      if (!data) {
        if (retryCount.current < maxRetries) {
           console.log(`Report not found, retrying... (${retryCount.current + 1}/${maxRetries})`);
           retryCount.current += 1;
           setTimeout(() => {
             fetchReport();
           }, 2000); 
           return;
        } else {
           console.log("Report generation timed out or failed.");
           setReport(null);
        }
      } else {
        setReport(data);
        retryCount.current = 0;
      }
    } catch (err) {
      console.error("Error fetching report:", err);
      setError(err.message);
    } finally {
      if (retryCount.current === 0 || retryCount.current >= maxRetries) {
        setLoading(false);
      }
    }
  }, [submissionId]);

  useEffect(() => {
    retryCount.current = 0;
    fetchReport();
  }, [fetchReport]);

  return { report, loading, error, refresh: fetchReport };
}
