import React, { useState, useEffect, useCallback } from 'react';
import api from '../services/api';

const fmt = (n, d = 1) => n != null ? Number(n).toFixed(d) : '—';
const fmtGiB = (bytes) => bytes != null ? (bytes / 1024 / 1024 / 1024).toFixed(1) + ' GB' : '—';
const fmtUptime = (s) => {
    if (!s) return '—';
    const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
    return d > 0 ? `${d}d ${h}h ${m}m` : `${h}h ${m}m`;
};
const fmtDate = (ts) => ts ? new Date(ts * 1000).toLocaleString('de-DE') : '—';
const STATUS_COLOR = { running: '#10B981', stopped: '#EF4444', paused: '#F59E0B', unknown: '#6B7280' };

function UsageBar({ used, total, label }) {
    const pct = total > 0 ? Math.min(100, (used / total) * 100) : 0;
    const color = pct >= 90 ? '#EF4444' : pct >= 70 ? '#F59E0B' : '#10B981';
    return (
        <div style={{ marginBottom: 12 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4, fontSize: 12 }}>
                <span style={{ color: 'var(--text-secondary)', fontWeight: 600 }}>{label}</span>
                <span style={{ color, fontWeight: 700 }}>{fmt(pct, 1)}%</span>
            </div>
            <div style={{ background: 'var(--bg-secondary)', borderRadius: 4, height: 8, overflow: 'hidden' }}>
                <div style={{ width: `${pct}%`, height: '100%', background: color, borderRadius: 4, transition: 'width .3s' }} />
            </div>
        </div>
    );
}

function StatusDot({ status }) {
    return <span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: '50%', background: STATUS_COLOR[status] || '#6B7280', marginRight: 6 }} />;
}

function StatBox({ label, value, color }) {
    return (
        <div style={{ background: 'var(--bg-secondary)', borderRadius: 10, padding: '12px 16px', textAlign: 'center' }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: color || 'var(--text-primary)', fontFamily: 'monospace' }}>{value}</div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{label}</div>
        </div>
    );
}

export default function ProxmoxPage() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [tab, setTab] = useState('overview');

    const load = useCallback(async () => {
        try {
            const r = await api.get('/proxmox/overview');
            setData(r.data);
            setError(null);
        } catch (e) {
            setError(e.response?.data?.error || 'Proxmox nicht erreichbar');
        }
        setLoading(false);
    }, []);

    useEffect(() => { load(); const t = setInterval(load, 30000); return () => clearInterval(t); }, [load]);

    if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>Verbinde mit Proxmox...</div>;
    if (error) return (
        <div style={{ padding: 40, textAlign: 'center' }}>
            <div style={{ fontSize: 48, marginBottom: 12 }}>⚠️</div>
            <div style={{ color: '#EF4444', fontWeight: 700, marginBottom: 8 }}>Proxmox nicht erreichbar</div>
            <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>{error}</div>
            <button className="btn btn-secondary" style={{ marginTop: 16 }} onClick={load}>🔄 Erneut versuchen</button>
        </div>
    );

    const { node, vms, lxcs, storage, tasks, disks, network, node_name, fetched_at } = data;
    const allGuests = [
        ...(vms || []).map(v => ({ ...v, type: 'VM' })),
        ...(lxcs || []).map(c => ({ ...c, type: 'CT' })),
    ].sort((a, b) => (a.vmid || 0) - (b.vmid || 0));

    const runningCount = allGuests.filter(g => g.status === 'running').length;
    const stoppedCount = allGuests.filter(g => g.status === 'stopped').length;
    const cpuPct = node ? (node.cpu || 0) * 100 : 0;
    const ramPct = node ? (node.memory?.used / node.memory?.total) * 100 : 0;
    const diskPct = node ? (node.rootfs?.used / node.rootfs?.total) * 100 : 0;

    return (
        <div style={{ padding: '28px' }}>
            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
                <div>
                    <h1 style={{ margin: 0, color: 'var(--text-primary)', fontSize: 24, fontWeight: 800 }}>
                        🖥️ Proxmox — {node_name}
                    </h1>
                    <p style={{ margin: '4px 0 0', color: 'var(--text-muted)', fontSize: 13 }}>
                        Uptime: {fmtUptime(node?.uptime)} · Kernel: {node?.kversion?.split(' ')[0] || '—'} · Aktualisiert: {fetched_at ? new Date(fetched_at).toLocaleTimeString('de-DE') : '—'}
                    </p>
                </div>
                <button className="btn btn-secondary" onClick={load}>🔄 Aktualisieren</button>
            </div>

            {/* Node Stats */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10, marginBottom: 24 }}>
                <StatBox label="CPU Usage" value={`${fmt(cpuPct)}%`} color={cpuPct >= 90 ? '#EF4444' : cpuPct >= 70 ? '#F59E0B' : '#10B981'} />
                <StatBox label="RAM Usage" value={`${fmt(ramPct)}%`} color={ramPct >= 90 ? '#EF4444' : ramPct >= 70 ? '#F59E0B' : '#10B981'} />
                <StatBox label="Root Disk" value={`${fmt(diskPct)}%`} color={diskPct >= 90 ? '#EF4444' : diskPct >= 70 ? '#F59E0B' : '#10B981'} />
                <StatBox label="VMs + CTs" value={allGuests.length} />
                <StatBox label="Laufend" value={runningCount} color="#10B981" />
                <StatBox label="Gestoppt" value={stoppedCount} color="#EF4444" />
                <StatBox label="Load Avg" value={node?.loadavg?.[0] ? fmt(node.loadavg[0]) : '—'} color={node?.loadavg?.[0] > 16 ? '#EF4444' : node?.loadavg?.[0] > 8 ? '#F59E0B' : '#10B981'} />
            </div>

            {/* Node Resource Bars */}
            <div style={{ background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: 12, padding: 20, marginBottom: 24 }}>
                <h3 style={{ margin: '0 0 16px', color: 'var(--text-primary)', fontSize: 15 }}>Node Ressourcen</h3>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
                    <div>
                        <UsageBar used={node?.cpu || 0} total={1} label={`CPU — ${node?.cpuinfo?.cpus || '?'} Kerne (${node?.cpuinfo?.model || ''})`} />
                        <UsageBar used={node?.memory?.used || 0} total={node?.memory?.total || 1} label={`RAM — ${fmtGiB(node?.memory?.used)} / ${fmtGiB(node?.memory?.total)}`} />
                        <UsageBar used={node?.rootfs?.used || 0} total={node?.rootfs?.total || 1} label={`Root FS — ${fmtGiB(node?.rootfs?.used)} / ${fmtGiB(node?.rootfs?.total)}`} />
                    </div>
                    <div>
                        {node?.swap?.total > 0 && <UsageBar used={node?.swap?.used || 0} total={node?.swap?.total || 1} label={`Swap — ${fmtGiB(node?.swap?.used)} / ${fmtGiB(node?.swap?.total)}`} />}
                        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 8 }}>
                            <div>Load: {node?.loadavg?.map(l => fmt(l)).join(' / ') || '—'}</div>
                            <div>CPUs: {node?.cpuinfo?.cpus || '?'} ({node?.cpuinfo?.cores || '?'} Kerne × {node?.cpuinfo?.sockets || '?'} Sockets)</div>
                            <div>IO Delay: {node?.wait != null ? `${fmt(node.wait * 100)}%` : '—'}</div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Tabs */}
            <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--border-color)', marginBottom: 24 }}>
                {[['overview', `🖥️ VMs & Container (${allGuests.length})`], ['storage', `💾 Storage (${(storage || []).length})`], ['tasks', `📋 Tasks`], ['network', `🌐 Netzwerk`]].map(([k, l]) => (
                    <button key={k} onClick={() => setTab(k)} style={{
                        background: 'none', border: 'none', borderBottom: tab === k ? '2px solid var(--cereda-primary)' : '2px solid transparent',
                        color: tab === k ? 'var(--cereda-primary)' : 'var(--text-secondary)',
                        padding: '10px 18px', cursor: 'pointer', fontWeight: tab === k ? 700 : 400, fontSize: 14, marginBottom: -1,
                    }}>{l}</button>
                ))}
            </div>

            {/* VMs & Container */}
            {tab === 'overview' && (
                <div style={{ background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: 12, overflow: 'hidden' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                            <tr style={{ background: 'var(--bg-secondary)', borderBottom: '1px solid var(--border-color)' }}>
                                {['ID', 'Typ', 'Name', 'Status', 'CPU', 'RAM', 'Disk', 'Uptime'].map(h => (
                                    <th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontSize: 12, color: 'var(--text-muted)', fontWeight: 600 }}>{h}</th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {allGuests.map(g => {
                                const cpuU = (g.cpu || 0) * 100;
                                const ramU = g.mem && g.maxmem ? (g.mem / g.maxmem) * 100 : 0;
                                const diskU = g.disk && g.maxdisk ? (g.disk / g.maxdisk) * 100 : 0;
                                return (
                                    <tr key={`${g.type}-${g.vmid}`} style={{ borderBottom: '1px solid var(--border-color)' }}>
                                        <td style={{ padding: '10px 14px', fontFamily: 'monospace', color: 'var(--text-muted)', fontSize: 12 }}>{g.vmid}</td>
                                        <td style={{ padding: '10px 14px' }}>
                                            <span style={{ padding: '2px 8px', borderRadius: 10, fontSize: 11, fontWeight: 700, background: g.type === 'VM' ? 'rgba(59,130,246,0.12)' : 'rgba(139,92,246,0.12)', color: g.type === 'VM' ? '#3B82F6' : '#8B5CF6' }}>{g.type}</span>
                                        </td>
                                        <td style={{ padding: '10px 14px', fontWeight: 600, color: 'var(--text-primary)', fontSize: 13 }}>{g.name}</td>
                                        <td style={{ padding: '10px 14px' }}>
                                            <span style={{ display: 'inline-flex', alignItems: 'center', fontSize: 12, fontWeight: 700, color: STATUS_COLOR[g.status] || '#6B7280' }}>
                                                <StatusDot status={g.status} />{g.status}
                                            </span>
                                        </td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: cpuU > 80 ? '#EF4444' : 'var(--text-secondary)' }}>
                                            {g.status === 'running' ? `${fmt(cpuU)}%` : '—'}
                                        </td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: ramU > 80 ? '#EF4444' : 'var(--text-secondary)' }}>
                                            {g.status === 'running' && g.maxmem ? `${fmtGiB(g.mem)} / ${fmtGiB(g.maxmem)}` : '—'}
                                        </td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: 'var(--text-muted)' }}>
                                            {g.maxdisk ? fmtGiB(g.maxdisk) : '—'}
                                        </td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: 'var(--text-muted)' }}>
                                            {g.status === 'running' ? fmtUptime(g.uptime) : '—'}
                                        </td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            )}

            {/* Storage */}
            {tab === 'storage' && (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 14 }}>
                    {(storage || []).filter(s => s.active).map(s => {
                        const pct = s.total > 0 ? (s.used / s.total) * 100 : 0;
                        const color = pct >= 90 ? '#EF4444' : pct >= 70 ? '#F59E0B' : '#10B981';
                        return (
                            <div key={s.storage} style={{ background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: 12, padding: 18 }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
                                    <div>
                                        <div style={{ fontWeight: 700, color: 'var(--text-primary)', fontSize: 14 }}>{s.storage}</div>
                                        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{s.type} · {(s.content || '').replace(/,/g, ', ')}</div>
                                    </div>
                                    <span style={{ fontSize: 12, fontWeight: 700, color }}>{fmt(pct)}%</span>
                                </div>
                                {s.total > 0 ? (
                                    <>
                                        <div style={{ background: 'var(--bg-secondary)', borderRadius: 4, height: 8, overflow: 'hidden', marginBottom: 8 }}>
                                            <div style={{ width: `${pct}%`, height: '100%', background: color, borderRadius: 4 }} />
                                        </div>
                                        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                                            {fmtGiB(s.used)} belegt / {fmtGiB(s.total)} gesamt · {fmtGiB(s.avail)} frei
                                        </div>
                                    </>
                                ) : (
                                    <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Keine Kapazitätsdaten</div>
                                )}
                            </div>
                        );
                    })}
                </div>
            )}

            {/* Tasks */}
            {tab === 'tasks' && (
                <div style={{ background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: 12, overflow: 'hidden' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                            <tr style={{ background: 'var(--bg-secondary)', borderBottom: '1px solid var(--border-color)' }}>
                                {['Typ', 'ID', 'Benutzer', 'Status', 'Gestartet', 'Dauer'].map(h => (
                                    <th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontSize: 12, color: 'var(--text-muted)', fontWeight: 600 }}>{h}</th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {(tasks || []).map((t, i) => {
                                const ok = t.status === 'OK';
                                const running = !t.endtime;
                                const dur = t.endtime && t.starttime ? `${t.endtime - t.starttime}s` : running ? 'läuft...' : '—';
                                return (
                                    <tr key={i} style={{ borderBottom: '1px solid var(--border-color)' }}>
                                        <td style={{ padding: '10px 14px', fontFamily: 'monospace', fontSize: 12, color: 'var(--text-secondary)' }}>{t.type}</td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: 'var(--text-muted)' }}>{t.id || '—'}</td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: 'var(--text-muted)' }}>{t.user}</td>
                                        <td style={{ padding: '10px 14px' }}>
                                            <span style={{ padding: '2px 8px', borderRadius: 10, fontSize: 11, fontWeight: 700, background: running ? 'rgba(59,130,246,0.12)' : ok ? 'rgba(16,185,129,0.12)' : 'rgba(239,68,68,0.12)', color: running ? '#3B82F6' : ok ? '#10B981' : '#EF4444' }}>
                                                {running ? 'Läuft' : t.status}
                                            </span>
                                        </td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: 'var(--text-muted)' }}>{fmtDate(t.starttime)}</td>
                                        <td style={{ padding: '10px 14px', fontSize: 12, color: 'var(--text-muted)' }}>{dur}</td>
                                    </tr>
                                );
                            })}
                            {(!tasks || tasks.length === 0) && (
                                <tr><td colSpan={6} style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>Keine Tasks</td></tr>
                            )}
                        </tbody>
                    </table>
                </div>
            )}

            {/* Network */}
            {tab === 'network' && (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14 }}>
                    {(network || []).filter(n => n.type === 'bridge' || n.type === 'eth' || n.type === 'bond').map(n => (
                        <div key={n.iface} style={{ background: 'var(--bg-card)', border: '1px solid var(--border-color)', borderRadius: 12, padding: 18 }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                                <span style={{ fontWeight: 700, color: 'var(--text-primary)', fontSize: 14 }}>{n.iface}</span>
                                <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 10, background: n.active ? 'rgba(16,185,129,0.12)' : 'rgba(107,114,128,0.12)', color: n.active ? '#10B981' : '#6B7280', fontWeight: 700 }}>{n.active ? 'Aktiv' : 'Inaktiv'}</span>
                            </div>
                            <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.8 }}>
                                <div>Typ: {n.type}</div>
                                {n.address && <div>IP: {n.address}/{n.netmask || ''}</div>}
                                {n.gateway && <div>Gateway: {n.gateway}</div>}
                                {n.bridge_ports && <div>Ports: {n.bridge_ports}</div>}
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
