
import { Upload, X } from 'lucide-react';
import { useLanguage } from '@/lib/language-context';
import React, { useCallback, useEffect, useState } from 'react';
import { useDropzone } from 'react-dropzone';

interface FileUploadProps {
    onFileSelect: (file: File) => void;
    accept?: Record<string, string[]>;
    maxSize?: number; // in bytes
    label?: string;
    className?: string;
    previewUrl?: string; // Initial preview URL
    previewMode?: 'cover' | 'contain';
    previewBoxClassName?: string;
}

export function FileUpload({
    onFileSelect,
    accept = { 'image/*': ['.png', '.jpg', '.jpeg', '.gif'] },
    maxSize = 5 * 1024 * 1024, // 5MB
    label,
    className = '',
    previewUrl,
    previewMode = 'cover',
    previewBoxClassName = 'w-32 h-32'
}: FileUploadProps) {
    const { t } = useLanguage();
    const [file, setFile] = useState<File | null>(null);
    const [preview, setPreview] = useState<string | null>(previewUrl || null);
    const [error, setError] = useState<string | null>(null);
    const maxSizeMb = maxSize / 1024 / 1024;
    const dropLabel = label || t('common.imageUploadPrompt');

    useEffect(() => {
        if (!file) {
            setPreview(previewUrl || null);
        }
    }, [previewUrl, file]);

    const onDrop = useCallback((acceptedFiles: File[]) => {
        setError(null);
        if (acceptedFiles.length > 0) {
            const selectedFile = acceptedFiles[0];
            setFile(selectedFile);

            // Create preview
            const objectUrl = URL.createObjectURL(selectedFile);
            setPreview(objectUrl);

            onFileSelect(selectedFile);
        }
    }, [onFileSelect]);

    const { getRootProps, getInputProps, isDragActive } = useDropzone({
        onDrop,
        accept,
        maxSize,
        multiple: false,
        onDropRejected: (fileRejections) => {
            const rejection = fileRejections[0];
            if (rejection.errors[0].code === 'file-too-large') {
                setError(t('common.fileTooLarge').replace('{size}', `${maxSizeMb}MB`));
            } else {
                setError(rejection.errors[0].message);
            }
        }
    });

    const clearFile = (e: React.MouseEvent) => {
        e.stopPropagation();
        setFile(null);
        setPreview(null);
        // Maybe we should notify parent to clear? For now assuming simple select logic.
        // If we want to support clearing, we might need an onClear prop or handle null in onFileSelect
    };

    return (
        <div className={`w-full ${className}`}>
            <div
                {...getRootProps()}
                className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors
          ${isDragActive ? 'border-primary bg-primary/5' : 'border-gray-300 hover:border-primary/50'}
          ${error ? 'border-red-500 bg-red-50' : ''}
        `}
            >
                <input {...getInputProps()} />

                {preview ? (
                    <div className="relative inline-block">
                        <div className={`relative mx-auto rounded-lg overflow-hidden border border-gray-200 ${previewBoxClassName}`}>
                            <img
                                src={preview}
                                alt={t('common.previewImage')}
                                className={`w-full h-full ${previewMode === 'contain' ? 'object-contain' : 'object-cover'}`}
                            />
                        </div>
                        {file && (
                            <button
                                onClick={clearFile}
                                className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 shadow-sm hover:bg-red-600 focus:outline-hidden"
                            >
                                <X size={14} />
                            </button>
                        )}
                        <p className="mt-2 text-sm text-gray-500">{file ? file.name : t('common.currentImage')}</p>
                    </div>
                ) : (
                    <div className="flex flex-col items-center justify-center space-y-2">
                        <div className="p-3 bg-gray-100 rounded-full">
                            <Upload className="w-6 h-6 text-gray-500" />
                        </div>
                        <p className="text-sm font-medium text-gray-700">{dropLabel}</p>
                        <p className="text-xs text-gray-500">
                            {t('common.maxSize').replace('{size}', `${maxSizeMb}MB`)}
                        </p>
                    </div>
                )}

                {error && <p className="mt-2 text-sm text-red-500">{error}</p>}
            </div>
        </div>
    );
}
