import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';

const API = '';

export default function UploadMobile() {
    const { token } = useParams<{ token: string }>();
    const [status, setStatus] = useState<'checking' | 'ready' | 'uploading' | 'done' | 'error'>('checking');
    const [noteRef, setNoteRef] = useState('');
    const [nomPrenom, setNomPrenom] = useState('');
    const [files, setFiles] = useState<File[]>([]);
    const [errorMsg, setErrorMsg] = useState('');

    useEffect(() => {
        fetch(`${API}/api/upload/check/${token}`)
            .then(r => r.json())
            .then(d => {
                if (d.valid) {
                    setNoteRef(d.noteRef);
                    setNomPrenom(d.nomPrenom.replace('_', ' '));
                    setStatus('ready');
                } else {
                    setErrorMsg(d.error || 'Lien invalide');
                    setStatus('error');
                }
            })
            .catch(() => { setErrorMsg('Erreur réseau'); setStatus('error'); });
    }, [token]);

    const addFiles = (newFiles: FileList | null) => {
        if (!newFiles) return;
        const allowed = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
        const filtered = Array.from(newFiles).filter(f => allowed.includes(f.type));
        setFiles(prev => [...prev, ...filtered]);
    };

    const handleSubmit = async () => {
        if (!files.length) return;
        setStatus('uploading');
        const form = new FormData();
        files.forEach(f => form.append('files', f));
        try {
            const res = await fetch(`${API}/api/upload/submit/${token}`, { method: 'POST', body: form });
            const data = await res.json();
            if (!res.ok) throw new Error(data.error);
            setStatus('done');
        } catch (e: any) {
            setErrorMsg(e.message);
            setStatus('error');
        }
    };

    // ── Écrans ──
    if (status === 'checking') return (
        <Screen><div style={{ textAlign: 'center' }}><Spinner />Vérification du lien...</div></Screen>
    );

    if (status === 'error') return (
        <Screen>
            <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 56, marginBottom: 12 }}>❌</div>
                <h2 style={{ color: '#dc2626', margin: '0 0 8px' }}>Lien invalide</h2>
                <p style={{ color: '#64748b', fontSize: 14 }}>{errorMsg}</p>
                <p style={{ color: '#94a3b8', fontSize: 12 }}>Ce lien a peut-être expiré (30 min) ou a déjà été utilisé.</p>
            </div>
        </Screen>
    );

    if (status === 'done') return (
        <Screen>
            <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 64, marginBottom: 12 }}>✅</div>
                <h2 style={{ color: '#15803d', margin: '0 0 8px' }}>Justificatif envoyé !</h2>
                <p style={{ color: '#374151', fontSize: 15 }}>
                    Document joint à la note <strong style={{ color: '#6366f1' }}>{noteRef}</strong>
                </p>
                <p style={{ color: '#64748b', fontSize: 13 }}>Vous pouvez fermer cette page.</p>
            </div>
        </Screen>
    );

    return (
        <Screen>
            <div style={{ marginBottom: 24 }}>
                <h2 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 800, color: '#0f172a' }}>
                    📎 Justificatif
                </h2>
                <p style={{ margin: 0, fontSize: 13, color: '#64748b' }}>
                    Pour <strong>{nomPrenom}</strong> — note <strong style={{ color: '#6366f1' }}>{noteRef}</strong>
                </p>
            </div>

            {/* Bouton caméra arrière */}
            <label style={uploadZone('#eef2ff', '#6366f1')}>
                <span style={{ fontSize: 40, display: 'block', marginBottom: 8 }}>📷</span>
                <strong style={{ fontSize: 16, color: '#4f46e5' }}>Prendre une photo</strong>
                <span style={{ fontSize: 12, color: '#64748b', display: 'block', marginTop: 4 }}>
                    Caméra arrière — ticket, facture, reçu
                </span>
                <input type="file" accept="image/*" capture="environment" multiple
                    style={{ display: 'none' }} onChange={e => addFiles(e.target.files)} />
            </label>

            {/* Bouton galerie / PDF */}
            <label style={{ ...uploadZone('#f8fafc', '#cbd5e1'), marginTop: 12 }}>
                <span style={{ fontSize: 32, display: 'block', marginBottom: 4 }}>📁</span>
                <strong style={{ fontSize: 14, color: '#374151' }}>Depuis la galerie ou PDF</strong>
                <input type="file" accept="image/*,application/pdf" multiple
                    style={{ display: 'none' }} onChange={e => addFiles(e.target.files)} />
            </label>

            {/* Aperçu fichiers */}
            {files.length > 0 && (
                <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {files.map((f, i) => (
                        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: '#f0fdf4', border: '1px solid #a7f3d0', borderRadius: 12 }}>
                            <span style={{ fontSize: 20 }}>{f.type === 'application/pdf' ? '📄' : '🖼️'}</span>
                            <div style={{ flex: 1, overflow: 'hidden' }}>
                                <div style={{ fontSize: 13, fontWeight: 600, color: '#0f172a', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</div>
                                <div style={{ fontSize: 11, color: '#64748b' }}>
                                    {f.size < 1048576 ? `${(f.size / 1024).toFixed(0)} Ko` : `${(f.size / 1048576).toFixed(1)} Mo`}
                                </div>
                            </div>
                            {f.type.startsWith('image/') && (
                                <img src={URL.createObjectURL(f)} alt="" style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 8 }} />
                            )}
                            <button onClick={() => setFiles(files.filter((_, j) => j !== i))}
                                style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#ef4444', fontSize: 20, padding: '0 4px' }}>✕</button>
                        </div>
                    ))}
                </div>
            )}

            <button
                onClick={handleSubmit}
                disabled={files.length === 0 || status === 'uploading'}
                style={{
                    marginTop: 24, width: '100%', padding: '16px',
                    background: files.length === 0 ? '#e2e8f0' : 'linear-gradient(135deg,#6366f1,#4f46e5)',
                    color: files.length === 0 ? '#94a3b8' : '#fff',
                    border: 'none', borderRadius: 14, fontSize: 16, fontWeight: 700,
                    cursor: files.length === 0 ? 'not-allowed' : 'pointer',
                    fontFamily: '"Inter","Segoe UI",sans-serif',
                }}>
                {status === 'uploading' ? '⏳ Envoi en cours...' : `📤 Envoyer${files.length > 0 ? ` (${files.length} fichier${files.length > 1 ? 's' : ''})` : ''}`}
            </button>
        </Screen>
    );
}

// ── Helpers ──
function Screen({ children }: { children: React.ReactNode }) {
    return (
        <div style={{ minHeight: '100vh', background: '#f1f5f9', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, fontFamily: '"Inter","Segoe UI",sans-serif' }}>
            <div style={{ background: '#fff', borderRadius: 24, padding: 32, maxWidth: 420, width: '100%', boxShadow: '0 8px 32px rgba(0,0,0,.12)' }}>
                {children}
            </div>
        </div>
    );
}

function Spinner() {
    return <div style={{ width: 32, height: 32, border: '3px solid #e2e8f0', borderTop: '3px solid #6366f1', borderRadius: '50%', animation: 'spin 0.8s linear infinite', margin: '0 auto 12px' }} />;
}

function uploadZone(bg: string, border: string): React.CSSProperties {
    return { display: 'block', background: bg, border: `2px dashed ${border}`, borderRadius: 16, padding: '24px 20px', textAlign: 'center', cursor: 'pointer' };
}
