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

const fmtMB = b => b ? (b / 1024 / 1024).toFixed(0) + ' MB' : '—';
const fmtUptime = s => {
    if (!s) return '—';
    const now = Math.floor(Date.now() / 1000);
    const sec = now - s;
    const d = Math.floor(sec / 86400), h = Math.floor((sec % 86400) / 3600), m = Math.floor((sec % 3600) / 60);
    return d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;
};

const STATE_COLOR = { running: '#10B981', exited: '#EF4444', paused: '#F59E0B', created: '#6B7280', restarting: '#3B82F6' };
const STATE_LABEL = { running: 'Running', exited: 'Stopped', paused: 'Paused', created: 'Created', restarting: 'Restarting' };

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>
    );
}

function UsageBar({ pct, label }) {
    const color = pct >= 85 ? '#EF4444' : pct >= 60 ? '#F59E0B' : '#10B981';
    return (
        <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 3 }}>
                <span style={{ color: 'var(--text-muted)' }}>{label}</span>
                <span style={{ color, fontWeight: 700 }}>{pct}%</span>
            </div>
            <div style={{ background: 'var(--bg-secondary)', borderRadius: 4, height: 6, overflow: 'hidden' }}>
                <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: color, borderRadius: 4, transition: 'width .4s' }} />
            </div>
        </div>
    );
}

function LogModal({ container, onClose }) {
    const [logs, setLogs] = useState('Lade Logs...');
    const [lines, setLines] = useState(100);

    const load = useCallback(async () => {
        setLogs('Lade Logs...');
        try {
            const r = await api.get(`/docker/containers/${container.id}/logs?lines=${lines}`);
            setLogs(r.data.logs || '(keine Logs)');
        } catch (e) {
            setLogs('Fehler: ' + (e.response?.data?.error || e.message));
        }
    }, [container.id, lines]);

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

    return (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
            onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
            <div style={{ background: 'var(--bg-card)', borderRadius: 14, width: '85vw', maxWidth: 900, maxHeight: '80vh', display: 'flex', flexDirection: 'column', overflow: 'hidden', boxShadow: '0 25px 60px rgba(0,0,0,0.4)' }}>
                <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-color)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div>
                        <span style={{ fontWeight: 800, color: 'var(--text-primary)', fontSize: 15 }}>📋 Logs — {container.name}</span>
                        <span style={{ fontSize: 12, color: 'var(--text-muted)', marginLeft: 10 }}>{container.image}</span>
                    </div>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                        <select value={lines} onChange={e => setLines(Number(e.target.value))}
                            style={{ fontSize: 12, padding: '4px 8px', borderRadius: 6, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)' }}>
                            {[50, 100, 200, 500].map(n => <option key={n} value={n}>Letzte {n} Zeilen</option>)}
                        </select>
                        <button onClick={load} style={{ padding: '5px 12px', borderRadius: 6, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', cursor: 'pointer', fontSize: 12, color: 'var(--text-primary)' }}>🔄</button>
                        <button onClick={onClose} style={{ padding: '5px 12px', borderRadius: 6, border: 'none', background: '#EF4444', color: '#fff', cursor: 'pointer', fontSize: 12, fontWeight: 700 }}>✕</button>
                    </div>
                </div>
                <pre style={{ margin: 0, padding: 16, overflowY: 'auto', flex: 1, background: '#0d1117', color: '#a5f3a5', fontSize: 12, fontFamily: 'Cascadia Mono, Consolas, monospace', lineHeight: 1.6, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
                    {logs}
                </pre>
            </div>
        </div>
    );
}

export default function DockerPage() {
    const [containers, setContainers] = useState([]);
    const [stats, setStats] = useState({});
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [logContainer, setLogContainer] = useState(null);
    const [actionLoading, setActionLoading] = useState({});
    const [lastUpdate, setLastUpdate] = useState(null);

    const loadContainers = useCallback(async () => {
        try {
            const r = await api.get('/docker/containers');
            setContainers(r.data);
            setError(null);
            setLastUpdate(new Date());
        } catch (e) {
            setError(e.response?.data?.error || 'Docker nicht erreichbar');
        }
        setLoading(false);
    }, []);

    const loadStats = useCallback(async () => {
        try {
            const r = await api.get('/docker/stats');
            const m = {};
            r.data.forEach(s => { m[s.id] = s; });
            setStats(m);
        } catch { }
    }, []);

    useEffect(() => {
        loadContainers();
        loadStats();
        const t1 = setInterval(loadContainers, 15000);
        const t2 = setInterval(loadStats, 10000);
        return () => { clearInterval(t1); clearInterval(t2); };
    }, [loadContainers, loadStats]);

    const doAction = async (id, name, action) => {
        const labels = { start: 'Starte', stop: 'Stoppe', restart: 'Restartet' };
        if (action === 'stop' && !window.confirm(`${name} stoppen?`)) return;
        setActionLoading(p => ({ ...p, [id + action]: true }));
        try {
            await api.post(`/docker/containers/${id}/${action}`);
            setTimeout(loadContainers, 1500);
        } catch (e) {
            alert(`Fehler: ${e.response?.data?.error || e.message}`);
        }
        setActionLoading(p => ({ ...p, [id + action]: false }));
    };

    const running = containers.filter(c => c.state === 'running').length;
    const stopped = containers.filter(c => c.state === 'exited').length;

    if (loading) return <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-muted)' }}>Verbinde mit Docker...</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 }}>Docker nicht erreichbar</div>
            <div style={{ color: 'var(--text-muted)', fontSize: 13 }}>{error}</div>
            <button className="btn btn-secondary" style={{ marginTop: 16 }} onClick={loadContainers}>🔄 Erneut versuchen</button>
        </div>
    );

    return (
        <div style={{ padding: 28 }}>
            {logContainer && <LogModal container={logContainer} onClose={() => setLogContainer(null)} />}

            {/* 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 }}>🐳 Docker Container</h1>
                    <p style={{ margin: '4px 0 0', color: 'var(--text-muted)', fontSize: 13 }}>
                        Server: 192.168.0.194 · {containers.length} Container · Aktualisiert: {lastUpdate?.toLocaleTimeString('de-DE') || '—'}
                    </p>
                </div>
                <button className="btn btn-secondary" onClick={() => { loadContainers(); loadStats(); }}>🔄 Aktualisieren</button>
            </div>

            {/* Stats */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))', gap: 10, marginBottom: 24 }}>
                <StatBox label="Gesamt" value={containers.length} />
                <StatBox label="Running" value={running} color="#10B981" />
                <StatBox label="Stopped" value={stopped} color={stopped > 0 ? '#EF4444' : 'var(--text-muted)'} />
            </div>

            {/* Container Cards */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: 14 }}>
                {containers.map(c => {
                    const s = stats[c.id];
                    const color = STATE_COLOR[c.state] || '#6B7280';
                    const isRunning = c.state === 'running';
                    return (
                        <div key={c.id} style={{ background: 'var(--bg-card)', border: `1px solid var(--border-color)`, borderRadius: 12, overflow: 'hidden', borderTop: `3px solid ${color}` }}>
                            <div style={{ padding: '14px 18px' }}>
                                {/* Header row */}
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                                    <div>
                                        <div style={{ fontWeight: 800, color: 'var(--text-primary)', fontSize: 15 }}>{c.name}</div>
                                        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, fontFamily: 'monospace' }}>{c.image}</div>
                                    </div>
                                    <span style={{ padding: '3px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700, background: `${color}20`, color }}>
                                        ● {STATE_LABEL[c.state] || c.state}
                                    </span>
                                </div>

                                {/* Info row */}
                                <div style={{ display: 'flex', gap: 16, marginBottom: isRunning && s ? 12 : 0, flexWrap: 'wrap' }}>
                                    <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                                        ID: <span style={{ fontFamily: 'monospace', color: 'var(--text-secondary)' }}>{c.id}</span>
                                    </span>
                                    {isRunning && (
                                        <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                                            Laufzeit: <span style={{ color: 'var(--text-secondary)' }}>{fmtUptime(c.created)}</span>
                                        </span>
                                    )}
                                    {c.ports.filter(p => p.PublicPort).length > 0 && (
                                        <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                                            Ports: <span style={{ color: 'var(--cereda-primary)', fontFamily: 'monospace' }}>
                                                {c.ports.filter(p => p.PublicPort).map(p => p.PublicPort).join(', ')}
                                            </span>
                                        </span>
                                    )}
                                </div>

                                {/* Stats bars */}
                                {isRunning && s && (
                                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
                                        <UsageBar pct={s.cpuPct} label="CPU" />
                                        <UsageBar pct={s.memPct} label={`RAM (${fmtMB(s.memUsed)})`} />
                                    </div>
                                )}

                                {/* Actions */}
                                <div style={{ display: 'flex', gap: 6, borderTop: '1px solid var(--border-color)', paddingTop: 10 }}>
                                    {!isRunning && (
                                        <button onClick={() => doAction(c.id, c.name, 'start')} disabled={actionLoading[c.id + 'start']}
                                            style={{ padding: '5px 12px', borderRadius: 6, border: 'none', background: '#10B981', color: '#fff', cursor: 'pointer', fontSize: 12, fontWeight: 700, opacity: actionLoading[c.id + 'start'] ? 0.6 : 1 }}>
                                            ▶ Start
                                        </button>
                                    )}
                                    {isRunning && (
                                        <button onClick={() => doAction(c.id, c.name, 'stop')} disabled={actionLoading[c.id + 'stop']}
                                            style={{ padding: '5px 12px', borderRadius: 6, border: 'none', background: '#EF4444', color: '#fff', cursor: 'pointer', fontSize: 12, fontWeight: 700, opacity: actionLoading[c.id + 'stop'] ? 0.6 : 1 }}>
                                            ■ Stop
                                        </button>
                                    )}
                                    <button onClick={() => doAction(c.id, c.name, 'restart')} disabled={actionLoading[c.id + 'restart']}
                                        style={{ padding: '5px 12px', borderRadius: 6, border: 'none', background: '#F59E0B', color: '#fff', cursor: 'pointer', fontSize: 12, fontWeight: 700, opacity: actionLoading[c.id + 'restart'] ? 0.6 : 1 }}>
                                        🔄 Restart
                                    </button>
                                    <button onClick={() => setLogContainer(c)}
                                        style={{ padding: '5px 12px', borderRadius: 6, border: '1px solid var(--border-color)', background: 'var(--bg-secondary)', color: 'var(--text-primary)', cursor: 'pointer', fontSize: 12 }}>
                                        📋 Logs
                                    </button>
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}
