import React, { useState } from 'react';
import axios from 'axios';

const ChunkedUpload = () => {
    const [file, setFile] = useState<File | null>(null);
    const [uploadProgress, setUploadProgress] = useState<number>(0);

    // Handle file selection
    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files) {
            setFile(event.target.files[0]);
        }
    };

    // Upload the file in chunks
    const uploadFile = async () => {
        if (!file) return;

        const chunkSize = 1024 * 1024; // 1MB per chunk
        const totalChunks = Math.ceil(file.size / chunkSize);
        const fileId = `${file.name}-${Date.now()}`; // Unique file identifier
        let uploadedChunks = 0;

        for (let start = 0; start < file.size; start += chunkSize) {
            const chunk = file.slice(start, start + chunkSize);
            const chunkNumber = Math.ceil(start / chunkSize) + 1;

            try {
                await axios.post(`${import.meta.env.VITE_API_EMS_URL}/upload`, chunk, {
                    headers: {
                        'Content-Type': 'application/octet-stream',
                        'X-Chunk-Number': chunkNumber.toString(),
                        'X-Total-Chunks': totalChunks.toString(),
                        'X-File-Id': fileId,
                    },
                });
                uploadedChunks++;
                setUploadProgress((uploadedChunks / totalChunks) * 100);
            } catch (error) {
                console.error('Chunk upload failed', error);
                // Implement retry logic if needed
                break;
            }
        }
    };

    return (
        <div>
            <input type="file" onChange={handleFileChange} />
            <button onClick={uploadFile} disabled={!file}>
                Upload File
            </button>
            <div>Upload Progress: {uploadProgress.toFixed(2)}%</div>
        </div>
    );
};

export default ChunkedUpload;