import React, { useState, useEffect, useCallback } from 'react';
import externalAlertService from '../services/externalAlertService';
import { toast } from 'react-toastify';

const SC = { ok: '#34d399', warn: '#f59e0b', crit: '#ef4444', unknown: '#6b7280' };

const timeAgo = (iso) => {
    if (!iso) return '–';
    const m = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
    if (m < 1) return 'gerade eben';
    if (m < 60) return `vor ${m} Min.`;
    const h = Math.floor(m / 60);
    if (h < 24) return `vor ${h} Std.`;
    return `vor ${Math.floor(h / 24)} Tag(en)`;
};

const sevColor = (s) => s === 'CRIT' ? SC.crit : s === 'WARN' ? SC.warn : s === 'OK' ? SC.ok : SC.unknown;

const DefenderPage = () => {
    const [alerts, setAlerts]               = useState([]);
    const [loading, setLoading]             = useState(true);
    const [hideAcknowledged, setHideAcknowledged] = useState(true);
    const [expandedAlerts, setExpandedAlerts]     = useState({});

    const loadAlerts = useCallback(async () => {
        try {
            const all = await externalAlertService.getAll();
            setAlerts(all.filter(a => a.source === 'mdo'));
        } catch {
            toast.error('Fehler beim Laden');
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => {
        loadAlerts();
        const r = setInterval(loadAlerts, 60000);
        return () => clearInterval(r);
    }, [loadAlerts]);

    const handleAcknowledge = async (id) => {
        try { await externalAlertService.acknowledge(id); loadAlerts(); toast.success('Quittiert'); }
        catch { toast.error('Fehler'); }
    };
    const handleCreateTicket = async (id) => {
        try { await externalAlertService.createTicket(id); loadAlerts(); toast.success('Ticket erstellt'); }
        catch { toast.error('Fehler beim Erstellen'); }
    };
    const handleRemove = async (id) => {
        if (!window.confirm('Alert wirklich löschen?')) return;
        try { await externalAlertService.remove(id); loadAlerts(); toast.success('Gelöscht'); }
        catch { toast.error('Fehler'); }
    };

    const toggleExpand = (id) => setExpandedAlerts(p => ({ ...p, [id]: !p[id] }));

    const parseAi  = (alert) => { try { return alert.ai_analysis ? (typeof alert.ai_analysis === 'string' ? JSON.parse(alert.ai_analysis) : alert.ai_analysis) : null; } catch { return null; } };
    const parseRaw = (alert) => { try { return alert.raw_body ? (typeof alert.raw_body === 'string' ? JSON.parse(alert.raw_body) : alert.raw_body) : null; } catch { return null; } };

    const unacked    = alerts.filter(a => !a.acknowledged).length;
    const hiddenCount = alerts.filter(a => a.acknowledged).length;
    const visible    = hideAcknowledged ? alerts.filter(a => !a.acknowledged) : alerts;

    const labelStyle = { fontSize: 11, color: 'var(--text-muted)', minWidth: 150, flexShrink: 0 };
    const valStyle   = { fontSize: 12, color: 'var(--text-primary)', wordBreak: 'break-word' };
    const row = (label, val) => val ? (
        <div style={{ display: 'flex', gap: 8, padding: '4px 0', borderBottom: '1px solid var(--border-color)' }}>
            <span style={labelStyle}>{label}</span>
            <span style={valStyle}>{val}</span>
        </div>
    ) : null;

    const renderCard = (alert) => {
        const color    = sevColor(alert.severity);
        const expanded = expandedAlerts[alert.id];
        const ai       = parseAi(alert);
        const raw      = parseRaw(alert);

        return (
            <div key={alert.id} style={{
                background: 'var(--bg-secondary)',
                border: `1px solid ${alert.acknowledged ? 'var(--border-color)' : color + '44'}`,
                borderLeft: `4px solid ${color}`,
                borderRadius: 10,
                padding: '14px 16px',
                opacity: alert.acknowledged ? 0.65 : 1,
            }}>
                {/* Header */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                    <div style={{ flex: 1 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
                            <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 6, background: color + '22', color, border: `1px solid ${color}44`, letterSpacing: 1 }}>
                                {alert.severity}
                            </span>
                            {alert.acknowledged && <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 6, background: 'var(--bg-tertiary)', color: 'var(--text-muted)', border: '1px solid var(--border-color)' }}>✓ Quittiert</span>}
                            {alert.ticket_id    && <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 6, background: SC.ok + '22', color: SC.ok, border: `1px solid ${SC.ok}44` }}>🎫 Ticket #{alert.ticket_id}</span>}
                        </div>
                        <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>{alert.message}</div>
                        <div style={{ fontSize: 12, color: 'var(--text-muted)', display: 'flex', flexWrap: 'wrap', gap: 12 }}>
                            <span>👤 {alert.device || '(kein Benutzer)'}</span>
                            {alert.service    && <span>📂 {alert.service}</span>}
                            {alert.state_time && <span>🕐 {new Date(alert.state_time).toLocaleString('de-DE')}</span>}
                            <span>Eingang: {timeAgo(alert.created_at)}</span>
                        </div>
                    </div>
                    {/* Buttons */}
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
                        {!alert.ticket_id && (
                            <button onClick={() => handleCreateTicket(alert.id)} style={{ padding: '5px 12px', borderRadius: 7, border: `1px solid var(--accent)`, background: 'var(--accent)', color: '#fff', fontSize: 12, cursor: 'pointer', fontWeight: 600, whiteSpace: 'nowrap' }}>🎫 Ticket</button>
                        )}
                        {!alert.acknowledged && (
                            <button onClick={() => handleAcknowledge(alert.id)} style={{ padding: '5px 12px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', fontSize: 12, cursor: 'pointer', whiteSpace: 'nowrap' }}>✓ Quittieren</button>
                        )}
                        <button onClick={() => handleRemove(alert.id)} style={{ padding: '5px 12px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', fontSize: 12, cursor: 'pointer' }}>🗑</button>
                    </div>
                </div>

                {/* Metadata */}
                {raw && (
                    <div style={{ marginTop: 12, padding: '10px 12px', background: 'var(--bg-primary)', borderRadius: 8 }}>
                        {row('Kategorie',         raw.category)}
                        {row('Bedrohungsfamilie', raw.threatFamilyName)}
                        {row('Angriffsvektor',    ai?.attack_vector || (raw.attackTechniques || [])[0])}
                        {row('Bedrohungstyp',     ai?.threat_type)}
                        {row('Status (Defender)', alert.state_transition)}
                    </div>
                )}

                {/* KI-Toggle */}
                {(ai?.what || ai?.recommendation) && (
                    <button onClick={() => toggleExpand(alert.id)} style={{ marginTop: 10, padding: '4px 12px', borderRadius: 7, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', fontSize: 12, cursor: 'pointer' }}>
                        {expanded ? '▲ Weniger' : '▼ KI-Analyse anzeigen'}
                    </button>
                )}
                {!ai && <div style={{ marginTop: 8, fontSize: 11, color: 'var(--text-muted)' }}>⏳ KI-Analyse ausstehend…</div>}

                {/* KI-Detail */}
                {expanded && ai && (
                    <div style={{ marginTop: 12, padding: '12px', background: 'var(--bg-primary)', borderRadius: 8 }}>
                        {ai.what && (
                            <div style={{ marginBottom: 10 }}>
                                <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 4 }}>Was ist passiert?</div>
                                <div style={{ fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.6 }}>{ai.what}</div>
                            </div>
                        )}
                        {ai.recommendation && (
                            <div style={{ display: 'flex', gap: 5, padding: '8px 10px', borderRadius: 7, background: ai.action_needed ? `${SC.warn}12` : `${SC.ok}12`, border: `1px solid ${ai.action_needed ? SC.warn : SC.ok}30` }}>
                                <span style={{ flexShrink: 0 }}>{ai.action_needed ? '⚠️' : '✅'}</span>
                                <span style={{ fontSize: 12, color: 'var(--text-secondary)', lineHeight: 1.5 }}>{ai.recommendation}</span>
                            </div>
                        )}
                    </div>
                )}
            </div>
        );
    };

    if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>Laden…</div>;

    return (
        <div style={{ padding: 24 }}>
            {/* Titel */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
                <div>
                    <h1 style={{ fontSize: 22, fontWeight: 700, margin: 0 }}>🛡️ Microsoft Defender</h1>
                    <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>Microsoft Defender for Office 365 — Security Alerts</div>
                </div>
                <button onClick={loadAlerts} style={{ padding: '7px 16px', borderRadius: 8, border: '1px solid var(--border-color)', background: 'none', color: 'var(--text-muted)', fontSize: 13, cursor: 'pointer' }}>↻ Aktualisieren</button>
            </div>

            {/* Stats */}
            <div style={{ display: 'flex', gap: 12, marginBottom: 20 }}>
                {[
                    { label: 'Gesamt', value: alerts.length, color: 'var(--text-muted)' },
                    { label: 'Offen', value: unacked, color: unacked > 0 ? SC.crit : SC.ok },
                    { label: 'Kritisch', value: alerts.filter(a => a.severity === 'CRIT' && !a.acknowledged).length, color: SC.crit },
                    { label: 'Warnung', value: alerts.filter(a => a.severity === 'WARN' && !a.acknowledged).length, color: SC.warn },
                ].map(stat => (
                    <div key={stat.label} style={{ padding: '10px 18px', borderRadius: 10, background: 'var(--bg-secondary)', border: '1px solid var(--border-color)', textAlign: 'center', minWidth: 80 }}>
                        <div style={{ fontSize: 22, fontWeight: 700, color: stat.color }}>{stat.value}</div>
                        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{stat.label}</div>
                    </div>
                ))}
            </div>

            {/* Filter */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
                <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{alerts.length} Alert{alerts.length !== 1 ? 's' : ''} · {unacked} nicht quittiert</span>
                {hiddenCount > 0 && (
                    <button onClick={() => setHideAcknowledged(h => !h)} style={{ padding: '3px 10px', borderRadius: 7, border: '1px solid var(--border-color)', background: hideAcknowledged ? 'var(--accent)' : 'none', color: hideAcknowledged ? '#fff' : 'var(--text-muted)', fontSize: 11, cursor: 'pointer' }}>
                        {hideAcknowledged ? `✓ Quittierte ausgeblendet (${hiddenCount})` : `Quittierte ausblenden (${hiddenCount})`}
                    </button>
                )}
            </div>

            {/* Liste */}
            {visible.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 80, color: 'var(--text-muted)', fontSize: 14 }}>
                    ✅ Keine aktiven Microsoft Defender Alerts
                </div>
            ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {visible.map(renderCard)}
                </div>
            )}
        </div>
    );
};

export default DefenderPage;
