import React, { useState, useRef } from 'react';
import './VideoUploadDropzone.css';

function VideoUploadDropzone({ onVideoUpload }) {
    const [isDragOver, setIsDragOver] = useState(false);
    const [isUploading, setIsUploading] = useState(false);
    const fileInputRef = useRef(null);

    const handleDragOver = (e) => {
        e.preventDefault();
        setIsDragOver(true);
    };

    const handleDragLeave = (e) => {
        e.preventDefault();
        setIsDragOver(false);
    };

    const handleDrop = (e) => {
        e.preventDefault();
        setIsDragOver(false);
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileUpload(files[0]);
        }
    };

    const handleFileSelect = (e) => {
        const files = e.target.files;
        if (files.length > 0) {
            handleFileUpload(files[0]);
        }
    };

    const handleFileUpload = async (file) => {
        // Validate file type
        if (!file.type.startsWith('video/')) {
            alert('Please select a valid video file');
            return;
        }

        // Validate file size (e.g., max 100MB)
        const maxSize = 100 * 1024 * 1024; // 100MB
        if (file.size > maxSize) {
            alert('File size too large. Please select a file under 100MB');
            return;
        }

        setIsUploading(true);

        try {
            const formData = new FormData();
            formData.append('video', file);

            // Get auth token
            const token = localStorage.getItem('access_token');

            const response = await fetch('/api/upload-video', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            });

            if (!response.ok) {
                throw new Error(`Upload failed: ${response.statusText}`);
            }

            const result = await response.json();
            
            // Call the callback with the uploaded video URL
            if (onVideoUpload && result.video_url) {
                onVideoUpload(result.video_url);
            }

        } catch (error) {
            console.error('Upload error:', error);
            alert('Upload failed. Please try again.');
        } finally {
            setIsUploading(false);
            // Reset file input
            if (fileInputRef.current) {
                fileInputRef.current.value = '';
            }
        }
    };

    const handleClick = () => {
        fileInputRef.current?.click();
    };

    return (
        <div
            className={`video-dropzone ${isDragOver ? 'drag-over' : ''} ${isUploading ? 'uploading' : ''}`}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={handleClick}
        >
            <input
                ref={fileInputRef}
                type="file"
                accept="video/*"
                onChange={handleFileSelect}
                style={{ display: 'none' }}
            />
            
            {isUploading ? (
                <div className="upload-status">
                    <div className="spinner"></div>
                    <p>Uploading video...</p>
                </div>
            ) : (
                <div className="upload-prompt">
                    <div className="upload-icon">📹</div>
                    <p>Drag and drop a video file here</p>
                    <p className="upload-subtitle">or click to select</p>
                    <div className="supported-formats">
                        Supports: MP4, AVI, MOV, WebM
                    </div>
                </div>
            )}
        </div>
    );
}

export default VideoUploadDropzone;