// ID Card Uploader Component
const { useState, useRef, useEffect } = React;

const IDCardUploader = ({ projectId, project, onUpdate }) => {
    const toast = useToast();
    const [uploading, setUploading] = useState({ front: false, back: false });
    const [extracting, setExtracting] = useState(false);
    const frontInputRef = useRef();
    const backInputRef = useRef();

    // Local state to track uploads without waiting for parent refresh
    const [localUploaded, setLocalUploaded] = useState({
        front: !!project?.id_card_front_path,
        back: !!project?.id_card_back_path,
        frontAt: project?.id_card_front_uploaded_at,
        backAt: project?.id_card_back_uploaded_at
    });

    // Sync local state with project prop when it changes
    useEffect(() => {
        setLocalUploaded({
            front: !!project?.id_card_front_path,
            back: !!project?.id_card_back_path,
            frontAt: project?.id_card_front_uploaded_at,
            backAt: project?.id_card_back_uploaded_at
        });
    }, [project?.id_card_front_path, project?.id_card_back_path, project?.id_card_front_uploaded_at, project?.id_card_back_uploaded_at]);

    const hasFront = localUploaded.front;
    const hasBack = localUploaded.back;
    const hasAnyImage = hasFront || hasBack;

    const handleUpload = async (side, file) => {
        if (!file) return;

        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;
        }

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

        setUploading(prev => ({ ...prev, [side]: true }));
        try {
            await window.ApiUtils.uploadIdCardImage(projectId, side, file);
            // Update local state immediately to prevent blink
            const now = new Date().toISOString();
            setLocalUploaded(prev => ({
                ...prev,
                [side]: true,
                [side === 'front' ? 'frontAt' : 'backAt']: now
            }));
            toast(`Immagine ${side === 'front' ? 'fronte' : 'retro'} caricata`, 'success');
            // Background refresh parent data
            onUpdate?.();
        } catch (error) {
            toast(error.message || 'Errore durante il caricamento', 'error');
        } finally {
            setUploading(prev => ({ ...prev, [side]: false }));
        }
    };

    const handleDelete = async (side) => {
        try {
            await window.ApiUtils.deleteIdCardImage(projectId, side);
            // Update local state immediately to prevent blink
            setLocalUploaded(prev => ({
                ...prev,
                [side]: false,
                [side === 'front' ? 'frontAt' : 'backAt']: null
            }));
            toast(`Immagine ${side === 'front' ? 'fronte' : 'retro'} eliminata`, 'success');
            // Background refresh parent data
            onUpdate?.();
        } catch (error) {
            toast(error.message || 'Errore durante l\'eliminazione', 'error');
        }
    };

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

        setExtracting(true);
        try {
            const result = await window.ApiUtils.extractIdCardData(projectId);
            toast('Dati estratti con successo!', 'success');
            onUpdate?.();
        } catch (error) {
            toast(error.message || 'Errore durante l\'estrazione', 'error');
        } finally {
            setExtracting(false);
        }
    };

    const DropZone = ({ side, hasImage, uploading, inputRef }) => {
        const label = side === 'front' ? 'Fronte' : 'Retro';
        const uploadedAt = side === 'front' ? localUploaded.frontAt : localUploaded.backAt;

        return (
            <div className="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-2.5 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">Caricato</div>
                                {uploadedAt && (
                                    <div className="text-[10px] text-slate-500 truncate">
                                        {new Date(uploadedAt).toLocaleDateString('it-IT', {
                                            day: '2-digit', month: '2-digit', year: 'numeric'
                                        })}
                                    </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"
                                    disabled={uploading}
                                    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={() => handleDelete(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 => handleUpload(side, e.target.files[0])}
                            className="hidden"
                        />
                    </div>
                ) : (
                    <div
                        className={`border-2 border-dashed rounded-lg p-3 text-center cursor-pointer transition-colors ${
                            uploading
                                ? 'border-brand-400 bg-brand-50'
                                : 'border-slate-300 hover:border-brand-400 hover:bg-brand-50'
                        }`}
                        onClick={() => !uploading && inputRef.current?.click()}
                        onDragOver={e => e.preventDefault()}
                        onDrop={e => {
                            e.preventDefault();
                            if (!uploading) handleUpload(side, e.dataTransfer.files[0]);
                        }}
                    >
                        {uploading ? (
                            <>
                                <Spinner className="mx-auto mb-1" size="sm" />
                                <p className="text-xs text-slate-600">Caricamento...</p>
                            </>
                        ) : (
                            <>
                                <div className="text-xl 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 => handleUpload(side, e.target.files[0])}
                            className="hidden"
                        />
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="space-y-3">
            <div className="grid grid-cols-2 gap-2">
                <DropZone
                    side="front"
                    hasImage={hasFront}
                    uploading={uploading.front}
                    inputRef={frontInputRef}
                />
                <DropZone
                    side="back"
                    hasImage={hasBack}
                    uploading={uploading.back}
                    inputRef={backInputRef}
                />
            </div>

            <button
                onClick={handleExtract}
                disabled={!hasAnyImage || extracting}
                className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-brand-500 text-white text-xs font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
                {extracting ? (
                    <>
                        <Spinner size="sm" />
                        <span>Estrazione...</span>
                    </>
                ) : (
                    <>
                        <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="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>
                        <span>Estrai Dati</span>
                    </>
                )}
            </button>
        </div>
    );
};

window.IDCardUploader = IDCardUploader;
