import { useState, useRef } from "react"
import { Upload, X, File, FileImage, FileVideo, Plus } from "lucide-react"
import { Button } from "@/Components/UI/Button"

const FileUploadField = ({
    label,
    field,
    accept = "image/*,video/*",
    multiple = true,
    onChange,
    hint = "You can upload images or videos. Max size: 20MB per file.",
    maxFileSize = 20 * 1024 * 1024, // 20MB
    value = []
}) => {
    const [selectedFiles, setSelectedFiles] = useState(value || [])
    const [dragActive, setDragActive] = useState(false)
    const [errors, setErrors] = useState([])
    const fileInputRef = useRef(null)

    const validateFiles = (files) => {
        const newErrors = []
        const validFiles = []

        Array.from(files).forEach((file, index) => {
            // Check file size
            if (file.size > maxFileSize) {
                newErrors.push(`${file.name}: File size exceeds 20MB limit`)
                return
            }

            // Check file type
            const isImage = file.type.startsWith('image/')
            const isVideo = file.type.startsWith('video/')
            if (!isImage && !isVideo) {
                newErrors.push(`${file.name}: Only images and videos are allowed`)
                return
            }

            validFiles.push(file)
        })

        setErrors(newErrors)
        return validFiles
    }

    const handleFileChange = (e) => {
        const files = e.target.files
        if (!files) return

        const validFiles = validateFiles(files)
        const updatedFiles = multiple ? [...selectedFiles, ...validFiles] : validFiles.slice(0, 1)

        setSelectedFiles(updatedFiles)
        if (onChange) {
            onChange(multiple ? updatedFiles : updatedFiles[0])
        }

        // Reset input value to allow selecting same files again
        if (fileInputRef.current) {
            fileInputRef.current.value = ''
        }
    }

    const removeFile = (indexToRemove) => {
        const updatedFiles = selectedFiles.filter((_, index) => index !== indexToRemove)
        setSelectedFiles(updatedFiles)
        if (onChange) {
            onChange(multiple ? updatedFiles : null)
        }
    }

    const clearAllFiles = () => {
        setSelectedFiles([])
        setErrors([])
        if (onChange) {
            onChange(multiple ? [] : null)
        }
        if (fileInputRef.current) {
            fileInputRef.current.value = ''
        }
    }

    const handleDrag = (e) => {
        e.preventDefault()
        e.stopPropagation()
        if (e.type === "dragenter" || e.type === "dragover") {
            setDragActive(true)
        } else if (e.type === "dragleave") {
            setDragActive(false)
        }
    }

    const handleDrop = (e) => {
        e.preventDefault()
        e.stopPropagation()
        setDragActive(false)

        if (e.dataTransfer.files && e.dataTransfer.files[0]) {
            const validFiles = validateFiles(e.dataTransfer.files)
            const updatedFiles = multiple ? [...selectedFiles, ...validFiles] : validFiles.slice(0, 1)

            setSelectedFiles(updatedFiles)
            if (onChange) {
                onChange(multiple ? updatedFiles : updatedFiles[0])
            }
        }
    }

    const getFileIcon = (file) => {
        if (file.type.startsWith('image/')) {
            return <FileImage className="w-4 h-4 text-primary" />
        }
        if (file.type.startsWith('video/')) {
            return <FileVideo className="w-4 h-4 text-purple-500" />
        }
        return <File className="w-4 h-4 text-gray-500" />
    }

    const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 Bytes'
        const k = 1024
        const sizes = ['Bytes', 'KB', 'MB', 'GB']
        const i = Math.floor(Math.log(bytes) / Math.log(k))
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    return (
        <div className="space-y-4">
            <label className="block text-sm font-medium text-gray-900 dark:text-gray-100">
                {label}
            </label>

            {/* Upload Area */}
            <div
                className={`relative border-2 border-dashed rounded-xl p-8 transition-colors ${
                    dragActive
                        ? 'border-primary bg-primary/5 dark:bg-primary/10'
                        : 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500'
                }`}
                onDragEnter={handleDrag}
                onDragLeave={handleDrag}
                onDragOver={handleDrag}
                onDrop={handleDrop}
            >
                <input
                    ref={fileInputRef}
                    id={field}
                    type="file"
                    accept={accept}
                    multiple={multiple}
                    onChange={handleFileChange}
                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                />

                <div className="text-center">
                    <Upload className="mx-auto h-12 w-12 text-gray-400 dark:text-gray-500" />
                    <div className="mt-4">
                        <p className="text-sm text-gray-600 dark:text-gray-400">
                            <span className="font-medium text-primary hover:text-primary/80 cursor-pointer">
                                Click to upload
                            </span>
                            {' or drag and drop'}
                        </p>
                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            {multiple ? 'Images and videos up to 20MB each' : 'Image or video up to 20MB'}
                        </p>
                    </div>
                </div>
            </div>

            {/* Error Messages */}
            {errors.length > 0 && (
                <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3">
                    <div className="text-sm text-red-600 dark:text-red-400 space-y-1">
                        {errors.map((error, index) => (
                            <p key={index}>• {error}</p>
                        ))}
                    </div>
                </div>
            )}

            {/* Selected Files */}
            {selectedFiles.length > 0 && (
                <div className="space-y-3">
                    <div className="flex items-center justify-between">
                        <h4 className="text-sm font-medium text-gray-900 dark:text-gray-100">
                            Selected Files ({selectedFiles.length})
                        </h4>
                        {multiple && selectedFiles.length > 1 && (
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={clearAllFiles}
                                className="text-red-600 hover:text-red-700 border-red-200 hover:border-red-300"
                            >
                                Clear All
                            </Button>
                        )}
                    </div>

                    <div className="grid grid-cols-1 gap-2 max-h-60 overflow-y-auto">
                        {selectedFiles.map((file, index) => (
                            <div
                                key={`${file.name}-${index}`}
                                className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-zinc-800"
                            >
                                <div className="flex items-center space-x-3 min-w-0 flex-1">
                                    {getFileIcon(file)}
                                    <div className="min-w-0 flex-1">
                                        <p className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
                                            {file.name}
                                        </p>
                                        <p className="text-xs text-gray-500 dark:text-gray-400">
                                            {formatFileSize(file.size)}
                                        </p>
                                    </div>
                                </div>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="sm"
                                    onClick={() => removeFile(index)}
                                    className="ml-2 h-8 w-8 p-0 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400"
                                >
                                    <X className="w-4 h-4" />
                                </Button>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* Add More Button (for multiple uploads) */}
            {multiple && selectedFiles.length > 0 && (
                <Button
                    type="button"
                    variant="outline"
                    onClick={() => fileInputRef.current?.click()}
                    className="w-full border-dashed border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:border-gray-400 dark:hover:border-gray-500"
                >
                    <Plus className="w-4 h-4 mr-2" />
                    Add More Files
                </Button>
            )}

            {hint && (
                <p className="text-xs text-gray-500 dark:text-gray-400">
                    {hint}
                </p>
            )}
        </div>
    )
}

export default FileUploadField
