import React, { useEffect, useState, useRef } from 'react';

const C = {
    primary: '#3fa3a3',
    primaryDark: '#008487',
    text: '#333333',
    textMid: '#4B4F58',
    textLight: '#808285',
    bg: '#F6F7F8',
    border: '#e4e0df',
    white: '#FFFFFF',
};

const API = process.env.REACT_APP_API_URL || '/api';
const headers = () => ({ Authorization: `Bearer ${localStorage.getItem('token')}` });

const riskConfig = {
    hoch:     { color: '#DC2626', bg: '#FEF2F2', border: '#FECACA', label: 'Hohes Risiko',    icon: '🔴' },
    mittel:   { color: '#D97706', bg: '#FFFBEB', border: '#FDE68A', label: 'Mittleres Risiko', icon: '🟡' },
    niedrig:  { color: '#059669', bg: '#ECFDF5', border: '#A7F3D0', label: 'Niedrig',          icon: '🟢' },
    unbekannt:{ color: '#6B7280', bg: '#F9FAFB', border: '#E5E7EB', label: 'Unbekannt',        icon: '⚪' },
};

const fmt = (d) => d ? new Date(d).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '—';

export default function SecurityReportsPage() {
    const [reports, setReports] = useState([]);
    const [selected, setSelected] = useState(null);
    const [uploading, setUploading] = useState(false);
    const [uploadError, setUploadError] = useState('');
    const [dragging, setDragging] = useState(false);
    const [loading, setLoading] = useState(true);
    const fileRef = useRef();

    const load = async () => {
        try {
            setLoading(true);
            const res = await fetch(`${API}/security-reports`, { headers: headers() });
            const data = await res.json();
            setReports(data);
            if (data.length > 0 && !selected) setSelected(data[0]);
        } catch (e) { console.error(e); }
        finally { setLoading(false); }
    };

    useEffect(() => { load(); }, []);

    const handleFile = async (file) => {
        if (!file || file.type !== 'application/pdf') {
            setUploadError('Nur PDF-Dateien erlaubt'); return;
        }
        setUploadError('');
        setUploading(true);
        try {
            const fd = new FormData();
            fd.append('pdf', file);
            const res = await fetch(`${API}/security-reports/upload`, {
                method: 'POST', headers: headers(), body: fd,
            });
            const data = await res.json();
            if (!res.ok) { setUploadError(data.error || 'Fehler'); return; }
            await load();
            setSelected(data);
        } catch (e) { setUploadError('Verbindungsfehler'); }
        finally { setUploading(false); }
    };

    const handleDelete = async (id) => {
        if (!window.confirm('Report löschen?')) return;
        await fetch(`${API}/security-reports/${id}`, { method: 'DELETE', headers: headers() });
        const updated = reports.filter(r => r.id !== id);
        setReports(updated);
        if (selected?.id === id) setSelected(updated[0] || null);
    };

    const risk = riskConfig[selected?.risk_level] || riskConfig.unbekannt;
    const a = selected?.analysis || {};

    return (
        <div style={{ display: 'flex', height: 'calc(100vh - 60px)', background: C.bg, fontFamily: 'Lato, sans-serif' }}>

            {/* ── Linke Spalte: Liste + Upload ── */}
            <div style={{ width: 320, flexShrink: 0, background: C.white, borderRight: `1px solid ${C.border}`, display: 'flex', flexDirection: 'column' }}>
                <div style={{ padding: '20px 16px 12px', borderBottom: `1px solid ${C.border}` }}>
                    <h2 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: C.text }}>Security Reports</h2>
                    <p style={{ margin: '4px 0 0', fontSize: 12, color: C.textLight }}>Arctic Wolf M365 Analysen</p>
                </div>

                {/* Upload-Bereich */}
                <div style={{ padding: '12px 16px', borderBottom: `1px solid ${C.border}` }}>
                    <div
                        onDragOver={e => { e.preventDefault(); setDragging(true); }}
                        onDragLeave={() => setDragging(false)}
                        onDrop={e => { e.preventDefault(); setDragging(false); handleFile(e.dataTransfer.files[0]); }}
                        onClick={() => fileRef.current?.click()}
                        style={{
                            border: `2px dashed ${dragging ? C.primary : C.border}`,
                            borderRadius: 10,
                            padding: '16px 12px',
                            textAlign: 'center',
                            cursor: uploading ? 'not-allowed' : 'pointer',
                            background: dragging ? '#f0fafa' : C.bg,
                            transition: 'all .15s',
                        }}
                    >
                        <div style={{ fontSize: 24, marginBottom: 6 }}>{uploading ? '⏳' : '📄'}</div>
                        <div style={{ fontSize: 12, fontWeight: 600, color: C.primary }}>
                            {uploading ? 'Wird analysiert…' : 'PDF hochladen'}
                        </div>
                        <div style={{ fontSize: 11, color: C.textLight, marginTop: 2 }}>
                            {uploading ? 'Claude analysiert den Report…' : 'Drag & Drop oder klicken'}
                        </div>
                    </div>
                    <input ref={fileRef} type="file" accept=".pdf" style={{ display: 'none' }}
                        onChange={e => handleFile(e.target.files[0])} />
                    {uploadError && (
                        <div style={{ marginTop: 8, fontSize: 12, color: '#DC2626', background: '#FEF2F2', borderRadius: 6, padding: '6px 10px' }}>
                            {uploadError}
                        </div>
                    )}
                </div>

                {/* Report-Liste */}
                <div style={{ flex: 1, overflowY: 'auto' }}>
                    {loading ? (
                        <div style={{ padding: 24, textAlign: 'center', color: C.textLight, fontSize: 13 }}>Lädt…</div>
                    ) : reports.length === 0 ? (
                        <div style={{ padding: 24, textAlign: 'center', color: C.textLight, fontSize: 13 }}>
                            Noch keine Reports.<br />PDF hochladen um zu starten.
                        </div>
                    ) : reports.map(r => {
                        const rc = riskConfig[r.risk_level] || riskConfig.unbekannt;
                        const isActive = selected?.id === r.id;
                        return (
                            <div key={r.id} onClick={() => setSelected(r)}
                                style={{
                                    padding: '12px 16px', cursor: 'pointer',
                                    borderLeft: `3px solid ${isActive ? C.primary : 'transparent'}`,
                                    background: isActive ? '#f0fafa' : 'transparent',
                                    borderBottom: `1px solid ${C.border}`,
                                    transition: 'all .1s',
                                }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                                    <div style={{ flex: 1, minWidth: 0 }}>
                                        <div style={{ fontSize: 12, fontWeight: 700, color: C.text, marginBottom: 2 }}>
                                            {rc.icon} {r.report_period}
                                        </div>
                                        <div style={{ fontSize: 11, color: C.textLight, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                                            {r.original_filename}
                                        </div>
                                        <div style={{ fontSize: 10, color: C.textLight, marginTop: 2 }}>{fmt(r.created_at)}</div>
                                    </div>
                                    <button onClick={e => { e.stopPropagation(); handleDelete(r.id); }}
                                        style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#9CA3AF', fontSize: 14, padding: '0 0 0 8px' }}>
                                        🗑
                                    </button>
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>

            {/* ── Rechte Spalte: Detail ── */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '24px 28px' }}>
                {!selected ? (
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', color: C.textLight }}>
                        <div style={{ fontSize: 56, marginBottom: 16 }}>🛡️</div>
                        <p style={{ fontSize: 16, fontWeight: 600 }}>Noch kein Report ausgewählt</p>
                        <p style={{ fontSize: 13 }}>Lade einen Arctic Wolf PDF Report hoch</p>
                    </div>
                ) : (
                    <div style={{ maxWidth: 900 }}>

                        {/* Header */}
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
                            <div>
                                <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: C.text }}>
                                    M365 Security Report
                                </h1>
                                <p style={{ margin: '4px 0 0', fontSize: 14, color: C.textLight }}>
                                    {selected.report_period} · Hochgeladen von {selected.created_by_username || '—'}
                                </p>
                            </div>
                            <div style={{
                                background: risk.bg, border: `1px solid ${risk.border}`,
                                borderRadius: 20, padding: '6px 14px',
                                fontSize: 13, fontWeight: 700, color: risk.color,
                            }}>
                                {risk.icon} {risk.label}
                            </div>
                        </div>

                        {/* Summary */}
                        {a.summary && (
                            <div style={{
                                background: C.white, border: `1px solid ${C.border}`,
                                borderLeft: `4px solid ${C.primary}`,
                                borderRadius: 10, padding: '16px 20px', marginBottom: 20,
                            }}>
                                <div style={{ fontSize: 11, fontWeight: 700, color: C.primary, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                                    KI-Zusammenfassung
                                </div>
                                <p style={{ margin: 0, fontSize: 14, color: C.text, lineHeight: 1.6 }}>{a.summary}</p>
                            </div>
                        )}

                        {/* Stats-Kacheln */}
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
                            {[
                                { label: 'Gesamt Logins', value: (a.login_stats?.total || 0).toLocaleString('de-DE'), icon: '🔑', color: C.primary },
                                { label: 'Erfolgreich', value: (a.login_stats?.successful || 0).toLocaleString('de-DE'), icon: '✅', color: '#059669' },
                                { label: 'Fehlgeschlagen', value: (a.login_stats?.failed || 0).toLocaleString('de-DE'), icon: '❌', color: '#DC2626' },
                                { label: 'Erfolgsrate', value: `${(a.login_stats?.success_rate || 0).toFixed(1)}%`, icon: '📊', color: C.primaryDark },
                            ].map(stat => (
                                <div key={stat.label} style={{
                                    background: C.white, border: `1px solid ${C.border}`,
                                    borderRadius: 10, padding: '16px 18px',
                                }}>
                                    <div style={{ fontSize: 22, marginBottom: 8 }}>{stat.icon}</div>
                                    <div style={{ fontSize: 22, fontWeight: 700, color: stat.color }}>{stat.value}</div>
                                    <div style={{ fontSize: 12, color: C.textLight, marginTop: 2 }}>{stat.label}</div>
                                </div>
                            ))}
                        </div>

                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>

                            {/* Top Login Fehler */}
                            <Section title="Top Login-Fehler" icon="⚠️">
                                {(a.top_login_failures || []).length === 0 ? (
                                    <Empty text="Keine Daten" />
                                ) : (a.top_login_failures || []).map((f, i) => (
                                    <Row key={i}
                                        left={<><span style={{ fontWeight: 700, color: C.text, fontSize: 13 }}>{f.user}</span><br /><span style={{ fontSize: 11, color: C.textLight }}>{f.type}</span></>}
                                        right={<span style={{ fontWeight: 700, color: '#DC2626', fontSize: 14 }}>{f.count?.toLocaleString('de-DE')}×</span>}
                                    />
                                ))}
                            </Section>

                            {/* Nicht-europäische Logins */}
                            <Section title="Logins außerhalb Europa" icon="🌍">
                                {(a.non_european_logins || []).length === 0 ? (
                                    <Empty text="✅ Keine auffälligen Logins" green />
                                ) : (a.non_european_logins || []).map((l, i) => (
                                    <Row key={i}
                                        left={<>
                                            <span style={{ fontWeight: 700, color: C.text, fontSize: 12 }}>{l.user}</span><br />
                                            <span style={{ fontSize: 11, color: C.textLight }}>{l.country} · {l.ip}</span>
                                        </>}
                                        right={l.flagged
                                            ? <span style={{ fontSize: 11, background: '#FEF2F2', color: '#DC2626', padding: '2px 7px', borderRadius: 10, fontWeight: 600 }}>⚠️ Auffällig</span>
                                            : <span style={{ fontSize: 11, color: C.textLight }}>{l.count}×</span>
                                        }
                                    />
                                ))}
                            </Section>
                        </div>

                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>

                            {/* Wichtige Erkenntnisse */}
                            <Section title="Wichtige Erkenntnisse" icon="🔍">
                                {(a.key_findings || []).length === 0 ? <Empty text="Keine" /> :
                                    (a.key_findings || []).map((f, i) => (
                                        <div key={i} style={{ display: 'flex', gap: 8, padding: '6px 0', borderBottom: i < a.key_findings.length - 1 ? `1px solid ${C.border}` : 'none' }}>
                                            <span style={{ color: C.primary, flexShrink: 0 }}>›</span>
                                            <span style={{ fontSize: 13, color: C.text, lineHeight: 1.5 }}>{f}</span>
                                        </div>
                                    ))
                                }
                            </Section>

                            {/* Empfehlungen */}
                            <Section title="Empfehlungen" icon="💡">
                                {(a.recommendations || []).length === 0 ? <Empty text="Keine" /> :
                                    (a.recommendations || []).map((r, i) => (
                                        <div key={i} style={{ display: 'flex', gap: 8, padding: '6px 0', borderBottom: i < a.recommendations.length - 1 ? `1px solid ${C.border}` : 'none' }}>
                                            <span style={{ color: C.primaryDark, flexShrink: 0 }}>→</span>
                                            <span style={{ fontSize: 13, color: C.text, lineHeight: 1.5 }}>{r}</span>
                                        </div>
                                    ))
                                }
                            </Section>
                        </div>

                        {/* Weitere Metriken */}
                        <Section title="Weitere Ereignisse" icon="📋">
                            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                                <Metric label="SharePoint anonyme Links" value={a.sharepoint_anonymous_links || 0} warn={(a.sharepoint_anonymous_links || 0) > 10} />
                                <Metric label="Identity Protection Events" value={a.identity_protection_events || 0} warn={(a.identity_protection_events || 0) > 0} />
                                <Metric label="Neue Gruppen erstellt" value={(a.new_groups_created || []).length} />
                            </div>
                        </Section>

                    </div>
                )}
            </div>
        </div>
    );
}

const Section = ({ title, icon, children }) => (
    <div style={{ background: '#FFFFFF', border: `1px solid #e4e0df`, borderRadius: 10, overflow: 'hidden' }}>
        <div style={{ padding: '12px 16px', borderBottom: `1px solid #e4e0df`, background: '#F6F7F8', display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>{icon}</span>
            <span style={{ fontSize: 13, fontWeight: 700, color: '#333333' }}>{title}</span>
        </div>
        <div style={{ padding: '8px 16px' }}>{children}</div>
    </div>
);

const Row = ({ left, right }) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: `1px solid #e4e0df` }}>
        <div style={{ flex: 1, minWidth: 0 }}>{left}</div>
        <div style={{ flexShrink: 0, marginLeft: 8 }}>{right}</div>
    </div>
);

const Empty = ({ text, green }) => (
    <p style={{ margin: '8px 0', fontSize: 13, color: green ? '#059669' : '#808285' }}>{text}</p>
);

const Metric = ({ label, value, warn }) => (
    <div style={{ textAlign: 'center', padding: '12px 8px', background: warn ? '#FEF2F2' : '#F6F7F8', borderRadius: 8 }}>
        <div style={{ fontSize: 24, fontWeight: 700, color: warn ? '#DC2626' : '#3fa3a3' }}>{value}</div>
        <div style={{ fontSize: 11, color: '#808285', marginTop: 4 }}>{label}</div>
    </div>
);
