const { useState, useCallback } = React;

const FileUpload = ({ onFilesLoaded }) => {
    const [isDragging, setIsDragging] = useState(false);
    const [jsonFile, setJsonFile] = useState(null);
    const [videoFile, setVideoFile] = useState(null);
    const [error, setError] = useState(null);

    const handleDrag = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        if (e.type === "dragenter" || e.type === "dragover") {
            setIsDragging(true);
        } else if (e.type === "dragleave") {
            setIsDragging(false);
        }
    }, []);

    const processFiles = (files) => {
        let newJson = jsonFile;
        let newVideo = videoFile;
        let err = null;

        Array.from(files).forEach(file => {
            if (file.name.endsWith('.json')) {
                newJson = file;
            } else if (file.type.startsWith('video/') || file.name.match(/\.(mp4|mov|webm|mkv)$/i)) {
                newVideo = file;
            } else {
                err = "Unsupported file type. Please upload a JSON and a Video file.";
            }
        });

        if (err) setError(err);
        else setError(null);

        setJsonFile(newJson);
        setVideoFile(newVideo);
    };

    const handleDrop = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragging(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            processFiles(e.dataTransfer.files);
            e.dataTransfer.clearData();
        }
    }, [jsonFile, videoFile]);

    const handleInput = (e) => {
        if (e.target.files && e.target.files.length > 0) {
            processFiles(e.target.files);
        }
    };

    const handleStart = async () => {
        if (!jsonFile || !videoFile) {
            setError("Please upload both a JSON file and a Video file.");
            return;
        }

        try {
            const text = await jsonFile.text();
            const data = JSON.parse(text);
            const videoUrl = URL.createObjectURL(videoFile);
            onFilesLoaded({ data, videoUrl, videoFileName: videoFile.name });
        } catch (e) {
            setError("Failed to parse JSON file.");
            console.error(e);
        }
    };

    return (
        <div className="flex flex-col items-center justify-center min-h-[80vh] animate-fade-in">
            <div className="w-full max-w-2xl">
                <div
                    className={`
                        relative group rounded-3xl border-2 border-dashed p-12 transition-all duration-300 ease-out
                        ${isDragging
                            ? 'border-sky-500 bg-sky-500/10 scale-[1.02]'
                            : 'border-slate-700 bg-slate-900/50 hover:border-slate-600 hover:bg-slate-900'
                        }
                    `}
                    onDragEnter={handleDrag}
                    onDragLeave={handleDrag}
                    onDragOver={handleDrag}
                    onDrop={handleDrop}
                >
                    <input
                        type="file"
                        multiple
                        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
                        onChange={handleInput}
                        accept=".json,video/*"
                    />

                    <div className="flex flex-col items-center text-center space-y-6 pointer-events-none">
                        <div className={`
                            w-20 h-20 rounded-2xl flex items-center justify-center transition-colors duration-300
                            ${isDragging ? 'bg-sky-500/20' : 'bg-slate-800 group-hover:bg-slate-700'}
                        `}>
                            <svg className={`w-10 h-10 ${isDragging ? 'text-sky-400' : 'text-slate-400'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                            </svg>
                        </div>

                        <div>
                            <h3 className="text-2xl font-semibold text-slate-200 mb-2">
                                Drop your files here
                            </h3>
                            <p className="text-slate-400 max-w-md">
                                Upload the Video Intelligence <span className="text-sky-400 font-medium">JSON</span> output
                                and the source <span className="text-indigo-400 font-medium">Video</span> file.
                            </p>
                        </div>

                        <div className="flex gap-4 w-full justify-center">
                            <div className={`
                                px-4 py-2 rounded-lg flex items-center gap-3 transition-all
                                ${jsonFile ? 'bg-emerald-500/10 border border-emerald-500/20 text-emerald-400' : 'bg-slate-800/50 border border-slate-700 text-slate-500'}
                            `}>
                                <div className={`w-2 h-2 rounded-full ${jsonFile ? 'bg-emerald-400' : 'bg-slate-600'}`} />
                                <span className="text-sm font-medium">{jsonFile ? jsonFile.name : 'Waiting for JSON...'}</span>
                            </div>

                            <div className={`
                                px-4 py-2 rounded-lg flex items-center gap-3 transition-all
                                ${videoFile ? 'bg-indigo-500/10 border border-indigo-500/20 text-indigo-400' : 'bg-slate-800/50 border border-slate-700 text-slate-500'}
                            `}>
                                <div className={`w-2 h-2 rounded-full ${videoFile ? 'bg-indigo-400' : 'bg-slate-600'}`} />
                                <span className="text-sm font-medium">{videoFile ? videoFile.name : 'Waiting for Video...'}</span>
                            </div>
                        </div>
                    </div>
                </div>

                {error && (
                    <div className="mt-6 p-4 rounded-xl bg-red-500/10 border border-red-500/20 text-red-400 flex items-center gap-3 animate-slide-up">
                        <svg className="w-5 h-5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                        {error}
                    </div>
                )}

                {jsonFile && videoFile && (
                    <div className="mt-8 flex justify-center animate-slide-up">
                        <button
                            onClick={handleStart}
                            className="
                                px-8 py-4 bg-gradient-to-r from-sky-500 to-indigo-600 hover:from-sky-400 hover:to-indigo-500
                                text-white font-semibold rounded-xl shadow-lg shadow-sky-500/25 
                                transform transition-all duration-200 hover:scale-105 active:scale-95
                                flex items-center gap-2
                            "
                        >
                            <span>Launch Visualizer</span>
                            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
                            </svg>
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
};

window.FileUpload = FileUpload;
