/*
 * Copyright (c) 2023-2025 Datalayer, Inc.
 * Distributed under the terms of the Modified BSD License.
 */
import { useState } from 'react';
import axios from 'axios';
// import useRun from "./useRun.js";
import { useIAMStore } from '../state/index.js';
// TODO reuse useRun hook.
export const useUploadForm = (url) => {
    const [isSuccess, setIsSuccess] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [progress, setProgress] = useState(0);
    const { token } = useIAMStore();
    //  const { requestRun } = useRun();
    const reset = () => {
        setIsSuccess(false);
        setIsLoading(false);
        setProgress(0);
    };
    const uploadAndSubmit = async (formData) => {
        setIsLoading(true);
        try {
            const { data } = await axios.post(url, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    Authorization: `Bearer ${token}`,
                },
                onUploadProgress: progressEvent => {
                    const progress = (progressEvent.loaded / progressEvent.total) * 50;
                    setProgress(progress);
                },
                onDownloadProgress: progressEvent => {
                    const progress = 50 + (progressEvent.loaded / progressEvent.total) * 50;
                    setProgress(progress);
                },
            });
            setProgress(100);
            await new Promise(resolve => {
                setTimeout(() => resolve('success'), 500);
            });
            setIsSuccess(true);
            setIsLoading(false);
            setProgress(0);
            return data;
        }
        catch (error) {
            setIsLoading(false);
            setProgress(0);
            throw error;
        }
    };
    return { uploadAndSubmit, isSuccess, isLoading, progress, reset };
};
