// Upload Modal Component for ID Card Extraction
const { useState, useRef } = React;

const UploadModal = ({ onClose, onExtracted }) => {
    const toast = useToast();
    const [mode, setMode] = useState('single'); // 'single' or 'split'
    const [singleFile, setSingleFile] = useState(null);
    const [files, setFiles] = useState({ front: null, back: null });
    const [extracting, setExtracting] = useState(false);
    const singleInputRef = useRef();
    const frontInputRef = useRef();
    const backInputRef = useRef();

    const hasSingleFile = !!singleFile;
    const hasFront = !!files.front;
    const hasBack = !!files.back;
    const hasAnyImage = mode === 'single' ? hasSingleFile : (hasFront || hasBack);

    const validateFile = (file) => {
        if (!file) return false;

        const validTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
        if (!validTypes.includes(file.type)) {
            toast('Formato file non valido. Usa JPG, PNG, WebP o GIF', 'error');
            return false;
        }

        if (file.size > 10 * 1024 * 1024) {
            toast('File troppo grande. Massimo 10 MB', 'error');
            return false;
        }

        return true;
    };

    const handleSingleFileSelect = (file) => {
        if (!validateFile(file)) return;
        setSingleFile(file);
        toast('Immagine selezionata', 'info');
    };

    const handleFileSelect = (side, file) => {
        if (!validateFile(file)) return;
        setFiles(prev => ({ ...prev, [side]: file }));
        toast(`Immagine ${side === 'front' ? 'fronte' : 'retro'} selezionata`, 'info');
    };

    const handleRemoveFile = (side) => {
        setFiles(prev => ({ ...prev, [side]: null }));
    };

    const handleExtract = async () => {
        if (!hasAnyImage) {
            toast('Carica almeno un\'immagine del documento', 'error');
            return;
        }

        setExtracting(true);
        const formData = new FormData();

        if (mode === 'single') {
            formData.append('files', singleFile);
        } else {
            // Add files in order: front first, then back
            if (files.front) {
                formData.append('files', files.front);
            }
            if (files.back) {
                formData.append('files', files.back);
            }
        }

        try {
            const response = await fetch('/extract', { method: 'POST', body: formData });
            const data = await response.json();
            if (data.status === 'success') {
                toast('Dati estratti con successo!', 'success');
                onExtracted(data);
            } else if (data.status === 'empty') {
                toast('Nessun dato estratto dalle immagini', 'warning');
                onExtracted(data);
            } else {
                toast(data.message || 'Estrazione fallita', 'error');
            }
        } catch (error) {
            toast(`Errore: ${error.message}`, 'error');
        } finally {
            setExtracting(false);
        }
    };

    const DropZone = ({ side, file, inputRef }) => {
        const label = side === 'front' ? 'Fronte' : 'Retro';
        const hasImage = !!file;

        return (
            <div className="flex-1 min-w-0">
                <div className="text-xs font-medium text-slate-700 mb-1.5">{label}</div>
                {hasImage ? (
                    <div className="border border-slate-200 rounded-lg p-3 bg-slate-50">
                        <div className="flex items-center gap-2">
                            <div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                <svg className="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                </svg>
                            </div>
                            <div className="min-w-0 flex-1">
                                <div className="text-xs font-medium text-slate-900 truncate">{file.name}</div>
                                <div className="text-[10px] text-slate-500">
                                    {(file.size / 1024).toFixed(1)} KB
                                </div>
                            </div>
                            <div className="flex gap-1 flex-shrink-0">
                                <button
                                    onClick={() => inputRef.current?.click()}
                                    className="p-1.5 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded transition-colors"
                                    title="Sostituisci"
                                >
                                    <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                                    </svg>
                                </button>
                                <button
                                    onClick={() => handleRemoveFile(side)}
                                    className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-50 rounded transition-colors"
                                    title="Elimina"
                                >
                                    <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                        <input
                            ref={inputRef}
                            type="file"
                            accept="image/jpeg,image/png,image/webp,image/gif"
                            onChange={e => handleFileSelect(side, e.target.files[0])}
                            className="hidden"
                        />
                    </div>
                ) : (
                    <div
                        className="border-2 border-dashed border-slate-300 rounded-lg p-4 text-center cursor-pointer hover:border-brand-400 hover:bg-brand-50 transition-colors"
                        onClick={() => inputRef.current?.click()}
                        onDragOver={e => e.preventDefault()}
                        onDrop={e => {
                            e.preventDefault();
                            handleFileSelect(side, e.dataTransfer.files[0]);
                        }}
                    >
                        <div className="text-2xl mb-1">
                            {side === 'front' ? '🪪' : '🔄'}
                        </div>
                        <p className="text-xs text-slate-600">Trascina o clicca</p>
                        <p className="text-[10px] text-slate-400 mt-0.5">Max 10 MB</p>
                        <input
                            ref={inputRef}
                            type="file"
                            accept="image/jpeg,image/png,image/webp,image/gif"
                            onChange={e => handleFileSelect(side, e.target.files[0])}
                            className="hidden"
                        />
                    </div>
                )}
            </div>
        );
    };

    const SingleDropZone = () => {
        return (
            <div className="w-full">
                {hasSingleFile ? (
                    <div className="border border-slate-200 rounded-lg p-3 bg-slate-50">
                        <div className="flex items-center gap-2">
                            <div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                                <svg className="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                </svg>
                            </div>
                            <div className="min-w-0 flex-1">
                                <div className="text-xs font-medium text-slate-900 truncate">{singleFile.name}</div>
                                <div className="text-[10px] text-slate-500">
                                    {(singleFile.size / 1024).toFixed(1)} KB
                                </div>
                            </div>
                            <div className="flex gap-1 flex-shrink-0">
                                <button
                                    onClick={() => singleInputRef.current?.click()}
                                    className="p-1.5 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded transition-colors"
                                    title="Sostituisci"
                                >
                                    <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                                    </svg>
                                </button>
                                <button
                                    onClick={() => setSingleFile(null)}
                                    className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-50 rounded transition-colors"
                                    title="Elimina"
                                >
                                    <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                            </div>
                        </div>
                        <input
                            ref={singleInputRef}
                            type="file"
                            accept="image/jpeg,image/png,image/webp,image/gif"
                            onChange={e => handleSingleFileSelect(e.target.files[0])}
                            className="hidden"
                        />
                    </div>
                ) : (
                    <div
                        className="border-2 border-dashed border-slate-300 rounded-lg p-6 text-center cursor-pointer hover:border-brand-400 hover:bg-brand-50 transition-colors"
                        onClick={() => singleInputRef.current?.click()}
                        onDragOver={e => e.preventDefault()}
                        onDrop={e => {
                            e.preventDefault();
                            handleSingleFileSelect(e.dataTransfer.files[0]);
                        }}
                    >
                        <div className="text-3xl mb-2">🪪</div>
                        <p className="text-sm text-slate-600">Trascina o clicca per caricare</p>
                        <p className="text-xs text-slate-400 mt-1">JPG, PNG, WebP, GIF - Max 10 MB</p>
                        <input
                            ref={singleInputRef}
                            type="file"
                            accept="image/jpeg,image/png,image/webp,image/gif"
                            onChange={e => handleSingleFileSelect(e.target.files[0])}
                            className="hidden"
                        />
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
            <Card className="w-full max-w-lg m-4" onClick={e => e.stopPropagation()}>
                <div className="p-4 border-b border-slate-200 flex items-center justify-between">
                    <h3 className="font-semibold text-slate-900">🪪 Carica Documento di Identità</h3>
                    <button className="text-slate-400 hover:text-slate-600 text-2xl" onClick={onClose}>×</button>
                </div>
                <div className="p-6 space-y-4">
                    <p className="text-sm text-slate-600">
                        Carica le immagini del documento per estrarre automaticamente i dati.
                    </p>

                    {/* Mode Toggle */}
                    <div className="flex gap-2 p-1 bg-slate-100 rounded-lg">
                        <button
                            onClick={() => setMode('single')}
                            className={`flex-1 px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
                                mode === 'single'
                                    ? 'bg-white text-slate-900 shadow-sm'
                                    : 'text-slate-600 hover:text-slate-900'
                            }`}
                        >
                            Immagine singola
                        </button>
                        <button
                            onClick={() => setMode('split')}
                            className={`flex-1 px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
                                mode === 'split'
                                    ? 'bg-white text-slate-900 shadow-sm'
                                    : 'text-slate-600 hover:text-slate-900'
                            }`}
                        >
                            Fronte + Retro
                        </button>
                    </div>

                    {/* Upload Zones */}
                    {mode === 'single' ? (
                        <SingleDropZone />
                    ) : (
                        <div className="flex gap-4">
                            <DropZone side="front" file={files.front} inputRef={frontInputRef} />
                            <DropZone side="back" file={files.back} inputRef={backInputRef} />
                        </div>
                    )}

                    <div className="flex justify-end gap-3 pt-2">
                        <Button variant="secondary" onClick={onClose}>Annulla</Button>
                        <Button
                            variant="primary"
                            onClick={handleExtract}
                            disabled={!hasAnyImage || extracting}
                        >
                            {extracting ? (
                                <>
                                    <Spinner size="sm" />
                                    <span className="ml-2">Estrazione...</span>
                                </>
                            ) : (
                                <>
                                    <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                                    </svg>
                                    Estrai Dati
                                </>
                            )}
                        </Button>
                    </div>
                </div>
            </Card>
        </div>
    );
};

window.UploadModal = UploadModal;
