import { useCallback, useRef, useState } from 'react';
import { UploadManager } from './uploadManager';
import { UploadProgress } from '@nice/common';
import { UploadOptions } from './types';

export function useUpload(options: UploadOptions = {}) {
    const [progress, setProgress] = useState<Record<string, UploadProgress>>({});
    const [errors, setErrors] = useState<Record<string, Error>>({});
    const uploadManagerRef = useRef<UploadManager>();
    const getUploadManager = useCallback(() => {
        if (!uploadManagerRef.current) {
            uploadManagerRef.current = new UploadManager(options);
        }
        return uploadManagerRef.current;
    }, [options]);
    const upload = useCallback(async (files: File | File[]) => {
        const fileList = Array.isArray(files) ? files : [files];
        const manager = getUploadManager();
        const uploads = fileList.map(file => {
            return manager.uploadFile(file, {
                ...options,
                onProgress: (progress) => {
                    setProgress(prev => ({
                        ...prev,
                        [progress.identifier]: progress
                    }));
                    options.onProgress?.(progress);
                },
                onError: (error) => {
                    setErrors(prev => ({
                        ...prev,
                        [file.name]: error
                    }));
                    options.onError?.(error);
                }
            });
        });
        return Promise.all(uploads);
    }, [options, getUploadManager]);

    const pauseUpload = useCallback((identifier: string) => {
        getUploadManager().pauseUpload(identifier);
    }, [getUploadManager]);

    const resumeUpload = useCallback((file: File) => {
        return getUploadManager().resumeUpload(file, options);
    }, [getUploadManager, options]);

    return {
        upload,
        pauseUpload,
        resumeUpload,
        progress,
        errors
    };
}