import { useReactFlow } from "../xyflow/react.js";
import { useCallback, useState } from "react";
import { copyCanvasToClipboard, downloadCanvasAsImage, exportCanvasToImage } from "../utils/export-canvas.js";
function useExportCanvas() {
    const reactFlowInstance = useReactFlow();
    const [isExporting, setIsExporting] = useState(false);
    const [error, setError] = useState(null);
    const [lastResult, setLastResult] = useState(null);
    const exportToImage = useCallback(async (options)=>{
        setIsExporting(true);
        setError(null);
        await new Promise((resolve)=>setTimeout(resolve, 0));
        try {
            const result = await exportCanvasToImage(reactFlowInstance, options);
            setLastResult(result);
            return result;
        } catch (err) {
            const exportError = err instanceof Error ? err : new Error('Failed to export canvas');
            setError(exportError);
            return null;
        } finally{
            setIsExporting(false);
        }
    }, [
        reactFlowInstance
    ]);
    const downloadAsImage = useCallback(async (filename, options)=>{
        setIsExporting(true);
        setError(null);
        await new Promise((resolve)=>setTimeout(resolve, 0));
        try {
            await downloadCanvasAsImage(reactFlowInstance, filename, options);
        } catch (err) {
            const downloadError = err instanceof Error ? err : new Error('Failed to download canvas');
            setError(downloadError);
        } finally{
            setIsExporting(false);
        }
    }, [
        reactFlowInstance
    ]);
    const copyToClipboard = useCallback(async (options)=>{
        setIsExporting(true);
        setError(null);
        await new Promise((resolve)=>setTimeout(resolve, 0));
        try {
            await copyCanvasToClipboard(reactFlowInstance, options);
        } catch (err) {
            const copyError = err instanceof Error ? err : new Error('Failed to copy canvas to clipboard');
            setError(copyError);
        } finally{
            setIsExporting(false);
        }
    }, [
        reactFlowInstance
    ]);
    const clearError = useCallback(()=>{
        setError(null);
    }, []);
    return {
        isExporting,
        error,
        lastResult,
        exportToImage,
        downloadAsImage,
        copyToClipboard,
        clearError
    };
}
export { useExportCanvas };
