import React, { useState } from 'react';
import { useUpload } from '@nice/client'; // Assuming the previous hook is in this file

const FileUploadComponent: React.FC = () => {
    const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

    const {
        upload,
        pauseUpload,
        resumeUpload,
        progress,
        errors
    } = useUpload({
        // Optional configuration
        baseUrl: "http://localhost:3000/upload",
        onProgress: (progressInfo) => {
            console.log('Upload progress:', progressInfo);
        },
        onError: (error) => {
            console.error('Upload error:', error);
        }
    });

    const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files) {
            setSelectedFiles(Array.from(event.target.files));
        }
    };

    const handleUpload = async () => {
        try {
            await upload(selectedFiles);
            alert('Upload completed successfully!');
        } catch (error) {
            console.error('Upload failed:', error);
        }
    };

    const renderProgressBar = (fileName: string) => {
        const fileProgress = progress[fileName];
        if (!fileProgress) return null;

        return (
            <div>
                <p>{fileName}</p>
                <progress
                    value={fileProgress.percentage}
                    max="100"
                />
                <span>{fileProgress.percentage.toFixed(2)}%</span>
                {errors[fileName] && (
                    <p style={{ color: 'red' }}>
                        Error: {errors[fileName].message}
                    </p>
                )}
            </div>
        );
    };

    return (
        <div>
            <input
                type="file"
                multiple
                onChange={handleFileSelect}
            />
            <button
                onClick={handleUpload}
                disabled={selectedFiles.length === 0}
            >
                Upload Files
            </button>

            <div>
                <h3>Upload Progress</h3>
                {selectedFiles.map(file => renderProgressBar(file.name))}
            </div>
        </div>
    );
};

export default FileUploadComponent;