import React, { useState, useEffect, useCallback } from 'react';
import axios from 'axios';

// Alle 90 Balken zeigen den aktuellen Live-Status
const generateUptimeBars = (currentStatus) => {
    const s = currentStatus === 'ok' ? 'ok' : currentStatus === 'warn' ? 'warn' : 'error';
    return Array(90).fill(s);
};

const STATUS_COLOR = {
    ok: '#22c55e',
    warn: '#f59e0b',
    error: '#ef4444',
    checking: '#6b7280',
};

const STATUS_BG = {
    ok: 'rgba(34,197,94,0.12)',
    warn: 'rgba(245,158,11,0.12)',
    error: 'rgba(239,68,68,0.12)',
    checking: 'rgba(107,114,128,0.12)',
};

const STATUS_LABEL = {
    ok: 'Betriebsbereit',
    warn: 'Beeinträchtigt',
    error: 'Ausgefallen',
    checking: 'Wird geprüft…',
};

const HEADER_BG = {
    ok: 'linear-gradient(135deg, #14532d 0%, #166534 100%)',
    warn: 'linear-gradient(135deg, #78350f 0%, #92400e 100%)',
    error: 'linear-gradient(135deg, #7f1d1d 0%, #991b1b 100%)',
    checking: 'linear-gradient(135deg, #1f2937 0%, #374151 100%)',
};

const HEADER_TEXT = {
    ok: 'Alle Systeme betriebsbereit',
    warn: 'Teilweise Beeinträchtigungen',
    error: 'Systemausfall festgestellt',
    checking: 'Systemstatus wird geprüft…',
};

const UptimeBar = ({ bars }) => (
    <div style={{ display: 'flex', gap: '2px', flex: 1, height: '32px', alignItems: 'center' }}>
        {bars.map((status, i) => (
            <div
                key={i}
                title={`Tag -${89 - i}: ${STATUS_LABEL[status]}`}
                style={{
                    flex: 1,
                    height: i === 89 ? '32px' : '24px',
                    borderRadius: '2px',
                    background: STATUS_COLOR[status],
                    opacity: i === 89 ? 1 : 0.7 + (i / 89) * 0.3,
                    transition: 'height 0.2s',
                    cursor: 'default',
                    minWidth: 0,
                }}
            />
        ))}
    </div>
);

const calcUptime = (bars) => {
    const ok = bars.filter(b => b === 'ok' || b === 'warn').length;
    return ((ok / bars.length) * 100).toFixed(2);
};

const ServiceRow = ({ name, description, icon, status, responseMs, bars }) => (
    <div style={{
        background: 'var(--bg-card)',
        border: '1px solid var(--border-color)',
        borderRadius: '12px',
        padding: '20px 24px',
        marginBottom: '12px',
    }}>
        {/* Header Row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '14px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <span style={{ fontSize: '20px' }}>{icon}</span>
                <div>
                    <div style={{ fontWeight: '600', fontSize: '15px', color: 'var(--text-primary)' }}>{name}</div>
                    {description && <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: '1px' }}>{description}</div>}
                </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                {responseMs !== null && responseMs !== undefined && (
                    <span style={{ fontSize: '12px', color: 'var(--text-muted)' }}>{responseMs} ms</span>
                )}
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    background: STATUS_BG[status],
                    border: `1px solid ${STATUS_COLOR[status]}44`,
                    borderRadius: '20px',
                    padding: '4px 12px',
                }}>
                    <div style={{
                        width: '8px',
                        height: '8px',
                        borderRadius: '50%',
                        background: STATUS_COLOR[status],
                        boxShadow: status === 'ok' ? `0 0 6px ${STATUS_COLOR[status]}` : 'none',
                    }} />
                    <span style={{ fontSize: '12px', fontWeight: '600', color: STATUS_COLOR[status] }}>
                        {STATUS_LABEL[status]}
                    </span>
                </div>
            </div>
        </div>

        {/* Uptime Bars */}
        <UptimeBar bars={bars} />

        {/* Footer */}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px' }}>
            <span style={{ fontSize: '11px', color: 'var(--text-muted)' }}>Vor 90 Tagen</span>
            <span style={{ fontSize: '11px', color: 'var(--text-muted)', fontWeight: '600' }}>
                {calcUptime(bars)}% Verfügbarkeit
            </span>
            <span style={{ fontSize: '11px', color: 'var(--text-muted)' }}>Heute</span>
        </div>
    </div>
);

const HealthPage = () => {
    const [loading, setLoading] = useState(true);
    const [healthData, setHealthData] = useState(null);
    const [responseMs, setResponseMs] = useState(null);
    const [serverError, setServerError] = useState(null);
    const [dbStatus, setDbStatus] = useState('checking');
    const [authStatus, setAuthStatus] = useState('checking');
    const [lastChecked, setLastChecked] = useState(null);
    const [autoRefresh, setAutoRefresh] = useState(true);
    const [countdown, setCountdown] = useState(30);
    const [bars, setBars] = useState({});
    const [historyDays, setHistoryDays] = useState([]);

    const checkHealth = useCallback(async () => {
        setLoading(true);
        setServerError(null);
        setDbStatus('checking');
        setAuthStatus('checking');

        const start = performance.now();
        let apiStatus = 'error';
        let ms = null;

        try {
            const res = await axios.get('/api/health', { timeout: 8000 });
            ms = Math.round(performance.now() - start);
            setHealthData(res.data);
            setResponseMs(ms);
            setServerError(null);
            apiStatus = ms < 300 ? 'ok' : 'warn';
        } catch (e) {
            ms = Math.round(performance.now() - start);
            setServerError(e.message || 'Server nicht erreichbar');
            setHealthData(null);
            setResponseMs(ms);
            apiStatus = 'error';
        }

        setLastChecked(new Date());
        setLoading(false);
        setCountdown(30);

        // DB check – axios direkt (kein Interceptor-Redirect bei 401)
        let dbS = 'error';
        try {
            await axios.get('/api/assets/stats', { timeout: 5000 });
            dbS = 'ok';
        } catch (e) {
            const s = e.response?.status;
            dbS = (s === 401 || s === 403) ? 'ok' : 'error';
        }
        setDbStatus(dbS);

        // Auth check – axios direkt (kein Interceptor-Redirect bei 401)
        let authS = 'error';
        try {
            await axios.get('/api/auth/me', { timeout: 5000 });
            authS = 'ok';
        } catch (e) {
            const s = e.response?.status;
            authS = (s === 401 || s === 403) ? 'ok' : 'error';
        }
        setAuthStatus(authS);

        // Latenz-Status
        const latS = ms === null ? 'error' : ms < 100 ? 'ok' : ms < 400 ? 'warn' : 'error';

        // Echte History nachladen
        try {
            const histRes = await axios.get('/api/health/history');
            const histData = histRes.data;
            // Letzte Balken aus History, letzter = heute mit aktuellem Status
            const toBars = (overrideToday) => {
                if (!histData || histData.length === 0) return generateUptimeBars(overrideToday);
                const arr = histData.map((d, i) =>
                    i === histData.length - 1 ? overrideToday : d.status
                );
                // Auf 90 Tage auffüllen wenn weniger Daten vorhanden
                while (arr.length < 90) arr.unshift('ok');
                return arr.slice(-90);
            };
            setBars({
                api: toBars(apiStatus),
                db: toBars(dbS),
                auth: toBars(authS),
                latency: toBars(latS),
            });
            setHistoryDays(histData);
        } catch {
            setBars({
                api: generateUptimeBars(apiStatus),
                db: generateUptimeBars(dbS),
                auth: generateUptimeBars(authS),
                latency: generateUptimeBars(latS),
            });
        }
    }, []);

    useEffect(() => {
        checkHealth();
        // Historische Daten laden
        axios.get('/api/health/history').then(r => setHistoryDays(r.data)).catch(() => {});
    }, [checkHealth]);

    useEffect(() => {
        if (!autoRefresh) return;
        const iv = setInterval(() => {
            setCountdown(prev => {
                if (prev <= 1) { checkHealth(); return 30; }
                return prev - 1;
            });
        }, 1000);
        return () => clearInterval(iv);
    }, [autoRefresh, checkHealth]);

    const apiStatus = loading ? 'checking' : serverError ? 'error' : responseMs < 300 ? 'ok' : 'warn';
    const overallStatus = loading ? 'checking'
        : (serverError || dbStatus === 'error' || authStatus === 'error') ? 'error'
        : (dbStatus === 'warn' || authStatus === 'warn' || apiStatus === 'warn') ? 'warn'
        : 'ok';

    const services = [
        {
            key: 'api',
            name: 'API Server',
            description: 'REST-API und Backend-Dienste',
            icon: '🖥️',
            status: apiStatus,
            responseMs: responseMs,
        },
        {
            key: 'db',
            name: 'Datenbank',
            description: 'SQLite Datenbankverbindung',
            icon: '🗄️',
            status: dbStatus,
            responseMs: null,
        },
        {
            key: 'auth',
            name: 'Authentifizierung',
            description: 'JWT Auth-Service und Benutzersitzungen',
            icon: '🔐',
            status: authStatus,
            responseMs: null,
        },
        {
            key: 'latency',
            name: 'Antwortzeit',
            description: 'Server-Latenz vom Browser gemessen',
            icon: '⚡',
            status: loading ? 'checking' : responseMs < 100 ? 'ok' : responseMs < 400 ? 'warn' : 'error',
            responseMs: responseMs,
        },
    ];

    return (
        <div style={{ minHeight: '100vh', background: 'var(--bg-primary)' }}>
            {/* Standalone Header */}
            <div style={{
                background: 'var(--bg-card)',
                borderBottom: '1px solid var(--border-color)',
                padding: '12px 24px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
            }}>
                <div style={{ fontWeight: '700', fontSize: '16px', color: 'var(--text-primary)', letterSpacing: '-0.01em' }}>
                    IT Nexus
                </div>
                <a
                    href="/dashboard"
                    style={{ fontSize: '13px', color: 'var(--cereda-primary)', textDecoration: 'none', fontWeight: '600' }}
                >
                    Zum Dashboard →
                </a>
            </div>

            {/* Hero Status Banner */}
            <div style={{
                background: HEADER_BG[overallStatus],
                padding: '48px 24px 56px',
                textAlign: 'center',
                position: 'relative',
                overflow: 'hidden',
            }}>
                {/* Animated background circles */}
                <div style={{
                    position: 'absolute', top: '-40px', left: '-40px',
                    width: '200px', height: '200px', borderRadius: '50%',
                    background: 'rgba(255,255,255,0.03)', pointerEvents: 'none',
                }} />
                <div style={{
                    position: 'absolute', bottom: '-60px', right: '-20px',
                    width: '280px', height: '280px', borderRadius: '50%',
                    background: 'rgba(255,255,255,0.03)', pointerEvents: 'none',
                }} />

                <div style={{ position: 'relative' }}>
                    <div style={{ fontSize: '48px', marginBottom: '12px' }}>
                        {overallStatus === 'ok' ? '✅' : overallStatus === 'warn' ? '⚠️' : overallStatus === 'error' ? '🔴' : '🔄'}
                    </div>
                    <h1 style={{
                        color: '#fff',
                        fontSize: '28px',
                        fontWeight: '800',
                        margin: '0 0 8px 0',
                        letterSpacing: '-0.02em',
                    }}>
                        {HEADER_TEXT[overallStatus]}
                    </h1>
                    {lastChecked && (
                        <p style={{ color: 'rgba(255,255,255,0.6)', fontSize: '13px', margin: 0 }}>
                            Zuletzt geprüft: {lastChecked.toLocaleTimeString('de-DE')}
                        </p>
                    )}
                </div>
            </div>

            {/* Controls */}
            <div style={{
                maxWidth: '860px', margin: '-20px auto 0',
                background: 'var(--bg-card)',
                border: '1px solid var(--border-color)',
                borderRadius: '16px',
                padding: '14px 20px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                boxShadow: '0 4px 20px rgba(0,0,0,0.2)',
                position: 'relative',
                zIndex: 1,
            }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', color: 'var(--text-muted)' }}>
                    <span>🔄</span>
                    {autoRefresh
                        ? <span>Automatische Aktualisierung in <strong style={{ color: 'var(--text-primary)' }}>{countdown}s</strong></span>
                        : <span>Automatische Aktualisierung deaktiviert</span>
                    }
                </div>
                <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                    <label style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '13px', color: 'var(--text-secondary)', cursor: 'pointer' }}>
                        <input
                            type="checkbox"
                            checked={autoRefresh}
                            onChange={e => setAutoRefresh(e.target.checked)}
                            style={{ accentColor: 'var(--cereda-primary)', width: '14px', height: '14px' }}
                        />
                        Auto-Refresh
                    </label>
                    <button
                        onClick={checkHealth}
                        disabled={loading}
                        style={{
                            background: 'var(--bg-secondary)',
                            border: '1px solid var(--border-color)',
                            borderRadius: '8px',
                            color: 'var(--text-primary)',
                            padding: '6px 14px',
                            fontSize: '13px',
                            fontWeight: '600',
                            cursor: loading ? 'not-allowed' : 'pointer',
                            opacity: loading ? 0.6 : 1,
                        }}
                    >
                        {loading ? 'Prüfe…' : 'Jetzt prüfen'}
                    </button>
                </div>
            </div>

            {/* Services */}
            <div style={{ maxWidth: '860px', margin: '32px auto', padding: '0 24px 48px' }}>
                <h2 style={{
                    fontSize: '11px',
                    fontWeight: '700',
                    textTransform: 'uppercase',
                    letterSpacing: '0.1em',
                    color: 'var(--text-muted)',
                    marginBottom: '16px',
                }}>
                    Services
                </h2>

                {services.map(svc => (
                    <ServiceRow
                        key={svc.key}
                        name={svc.name}
                        description={svc.description}
                        icon={svc.icon}
                        status={svc.status}
                        responseMs={svc.responseMs}
                        bars={bars[svc.key] || Array(90).fill('checking')}
                    />
                ))}

                {/* Incidents */}
                <h2 style={{
                    fontSize: '11px',
                    fontWeight: '700',
                    textTransform: 'uppercase',
                    letterSpacing: '0.1em',
                    color: 'var(--text-muted)',
                    margin: '32px 0 16px',
                }}>
                    Vorfälle
                </h2>
                <div style={{
                    background: 'var(--bg-card)',
                    border: '1px solid var(--border-color)',
                    borderRadius: '12px',
                    padding: '24px',
                    textAlign: 'center',
                    color: 'var(--text-muted)',
                    fontSize: '14px',
                }}>
                    <div style={{ fontSize: '24px', marginBottom: '8px' }}>✓</div>
                    Keine Vorfälle in den letzten 90 Tagen
                </div>

                {/* Footer */}
                <div style={{ textAlign: 'center', marginTop: '32px', fontSize: '12px', color: 'var(--text-muted)' }}>
                    IT Nexus · Status-Seite ·{' '}
                    {healthData?.timestamp && (
                        <>Serverzeit: {new Date(healthData.timestamp).toLocaleString('de-DE')}</>
                    )}
                </div>
            </div>
        </div>
    );
};

export default HealthPage;
