import { useState, useRef, useCallback } from 'react';

export function useViolationReportOptimization() {
  const [isGenerating, setIsGenerating] = useState(false);
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState(null);
  
  const abortControllerRef = useRef(null);

  const startGeneration = useCallback(async (data, settings, generatorFn) => {
    setIsGenerating(true);
    setProgress(0);
    setError(null);

    if (abortControllerRef.current) {
        abortControllerRef.current.abort();
    }
    abortControllerRef.current = new AbortController();

    try {
        const doc = await generatorFn(
            data, 
            settings, 
            (p) => setProgress(p),
            abortControllerRef.current.signal
        );
        return doc;
    } catch (err) {
        if (err.message === 'Report generation cancelled') {
            console.log('Generation cancelled by user');
        } else {
            console.error("Report generation failed:", err);
            setError(err.message || 'Unknown error');
        }
        throw err;
    } finally {
        setIsGenerating(false);
        abortControllerRef.current = null;
    }
  }, []);

  const cancelGeneration = useCallback(() => {
      if (abortControllerRef.current) {
          abortControllerRef.current.abort();
          setIsGenerating(false);
      }
  }, []);

  return {
    isGenerating,
    progress,
    error,
    startGeneration,
    cancelGeneration
  };
}
