import React, { useState, useEffect } from 'react';
import { useOutletContext } from 'react-router-dom';
import { useSettings } from '../context/SettingsContext';
import {
    HardDrive,
    Cpu,
    MemoryStick,
    Network,
    Server,
    Activity,
    Clock,
    Loader2
} from 'lucide-react';
import {
    BarChart, Bar, LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell
} from 'recharts';

// API URL
const API_URL = '/api/stats';

const Dashboard = () => {
    const { chartType, hiddenInterfaces } = useSettings(); // Use Global Setting
    const [stats, setStats] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [history, setHistory] = useState([]);

    useEffect(() => {
        const fetchHistory = async () => {
            try {
                const response = await fetch('/api/history');
                const data = await response.json();

                // Get last 60 minutes (60 points)
                // Backend sends { timestamp, cpu, memory, network: {rx, tx} }
                // Frontend needs { time, cpu, memory, rx, tx }
                const formattedHistory = data.slice(-60).map(item => ({
                    time: new Date(item.timestamp).toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' }),
                    cpu: item.cpu,
                    memory: item.memory,
                    rx: item.network ? item.network.rx : 0,
                    tx: item.network ? item.network.tx : 0
                }));
                setHistory(formattedHistory);
            } catch (err) {
                console.error('Failed to fetch initial history:', err);
            }
        };
        fetchHistory();

        const fetchStats = async () => {
            try {
                const response = await fetch(API_URL);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const data = await response.json();
                setStats(data);

                // Update history for Line chart
                setHistory(prev => {
                    const now = new Date().toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });

                    // Calculate Total Network Traffic
                    let totalRx = 0;
                    let totalTx = 0;
                    if (data.network) {
                        data.network.forEach(net => {
                            if (!hiddenInterfaces?.includes(net.iface)) {
                                totalRx += (net.rx_sec || 0);
                                totalTx += (net.tx_sec || 0);
                            }
                        });
                    }

                    const newPoint = {
                        time: now,
                        cpu: data.cpu.load,
                        memory: data.memory.percentage,
                        rx: totalRx,
                        tx: totalTx
                    };
                    const newHistory = [...prev, newPoint];
                    // Keep last 1 hour (assuming 5s updates + initial 1m data mixed)
                    // 1 hour = 720 points at 5s interval.
                    if (newHistory.length > 720) newHistory.shift();
                    return newHistory;
                });

                setLoading(false);
            } catch (err) {
                console.error('Fetch error:', err);
                setError('Failed to connect to server. Ensure Backend is running.');
                setLoading(false);
            }
        };

        fetchStats();
        const interval = setInterval(fetchStats, 5000);

        return () => clearInterval(interval);
    }, []);

    if (loading) return (
        <div className="loading-container-center">
            <Loader2 className="spin-animation" size={48} />
        </div>
    );

    return (
        <div className="dashboard-container">
            {/* 
         Row 1: System Info Widget 
      */}
            <div className="glass-card system-info-card">
                <div className="sys-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <defs>
                            <linearGradient id="nasGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                                <stop offset="0%" stopColor="#dc2626" />
                                <stop offset="100%" stopColor="#ff8c00" />
                            </linearGradient>
                        </defs>
                        {/* NAS 외곽 케이스 */}
                        <rect x="3" y="4" width="18" height="16" rx="1.5" stroke="url(#nasGradient)" strokeWidth="1.8" fill="none" />
                        {/* 상단 LED 패널 라인 */}
                        <line x1="4" y1="7.5" x2="20" y2="7.5" stroke="url(#nasGradient)" strokeWidth="1" />
                        {/* Drive Bay 1 */}
                        <rect x="5" y="9" width="6" height="9" rx="0.8" stroke="url(#nasGradient)" strokeWidth="1.3" fill="none" />
                        {/* Drive Bay 2 */}
                        <rect x="13" y="9" width="6" height="9" rx="0.8" stroke="url(#nasGradient)" strokeWidth="1.3" fill="none" />
                        {/* LED 표시등 1 */}
                        <circle cx="7" cy="10.5" r="0.8" fill="url(#nasGradient)" />
                        {/* LED 표시등 2 */}
                        <circle cx="15" cy="10.5" r="0.8" fill="url(#nasGradient)" />
                        {/* HDD 슬롯 라인 Bay 1 */}
                        <line x1="6.5" y1="12.5" x2="9.5" y2="12.5" stroke="url(#nasGradient)" strokeWidth="0.6" opacity="0.6" />
                        <line x1="6.5" y1="14.5" x2="9.5" y2="14.5" stroke="url(#nasGradient)" strokeWidth="0.6" opacity="0.6" />
                        {/* HDD 슬롯 라인 Bay 2 */}
                        <line x1="14.5" y1="12.5" x2="17.5" y2="12.5" stroke="url(#nasGradient)" strokeWidth="0.6" opacity="0.6" />
                        <line x1="14.5" y1="14.5" x2="17.5" y2="14.5" stroke="url(#nasGradient)" strokeWidth="0.6" opacity="0.6" />
                        {/* 전원 버튼 */}
                        <circle cx="6" cy="6" r="0.6" stroke="url(#nasGradient)" strokeWidth="0.8" fill="none" />
                    </svg>
                </div>
                <div className="sys-details">
                    <h3 className="logo-text">{stats?.system?.model || 'Synology NAS'}</h3>
                    <p className="sys-subtitle">시스템 모니터</p>
                </div>
                <div className="sys-meta">
                    <div className="meta-item">
                        <span className="label">OS</span>
                        <span className="value">{stats?.system?.os}</span>
                    </div>
                    <div className="meta-item">
                        <span className="label">Version</span>
                        <span className="value">{stats?.system?.release}</span>
                    </div>
                    <div className="meta-item">
                        <span className="label">Kernel</span>
                        <span className="value">{stats?.system?.kernel}</span>
                    </div>
                </div>
            </div>

            {error && (
                <div className="glass-panel error-banner" style={{ background: 'rgba(239, 68, 68, 0.1)', border: '1px solid var(--error-color)', color: 'var(--error-color)', padding: '1rem', marginBottom: '1.5rem', borderRadius: '12px' }}>
                    {error}
                </div>
            )}

            {/* 
         Row 2: CPU & Memory (Half Width Each)
      */}
            <div className="resource-row">
                {/* CPU Widget */}
                <div className="glass-card resource-card">
                    <div className="card-header-simple">
                        <div className="header-left">
                            <Cpu size={20} className="card-icon" />
                            <h3>CPU</h3>
                        </div>
                        <span className="percentage-value" style={{ color: 'var(--cpu-color)' }}>{stats?.cpu?.load}%</span>
                    </div>

                    {chartType === 'line' ? (
                        <div className="chart-wrapper">
                            <ResponsiveContainer width="100%" height={100}>
                                <LineChart data={history}>
                                    <Line type="monotone" dataKey="cpu" stroke="var(--cpu-color)" strokeWidth={2} dot={false} isAnimationActive={false} />
                                    <YAxis domain={[0, 100]} hide />
                                </LineChart>
                            </ResponsiveContainer>
                        </div>
                    ) : (
                        <div className="progress-container">
                            <div
                                className="progress-fill"
                                style={{
                                    width: `${stats?.cpu?.load}%`,
                                    backgroundColor: stats?.cpu?.load > 80 ? 'var(--error-color)' : 'var(--cpu-color)'
                                }}
                            />
                        </div>
                    )}
                </div>

                {/* Memory Widget */}
                <div className="glass-card resource-card">
                    <div className="card-header-simple">
                        <div className="header-left">
                            <MemoryStick size={20} className="card-icon" />
                            <h3>메모리</h3>
                        </div>
                        <span className="percentage-value" style={{ color: 'var(--success-color)' }}>{stats?.memory?.percentage}%</span>
                    </div>

                    {chartType === 'line' ? (
                        <div className="chart-wrapper">
                            <ResponsiveContainer width="100%" height={100}>
                                <LineChart data={history}>
                                    <Line type="monotone" dataKey="memory" stroke="var(--success-color)" strokeWidth={2} dot={false} isAnimationActive={false} />
                                    <YAxis domain={[0, 100]} hide />
                                </LineChart>
                            </ResponsiveContainer>
                        </div>
                    ) : (
                        <div className="progress-container">
                            <div
                                className="progress-fill"
                                style={{
                                    width: `${stats?.memory?.percentage}%`,
                                    backgroundColor: stats?.memory?.percentage > 80 ? 'var(--error-color)' : 'var(--success-color)'
                                }}
                            />
                        </div>
                    )}
                </div>
            </div>

            {/* 
         Row 3: Disk Usage
      */}
            <div className="glass-card disk-card">
                <div className="card-header-simple mb-3">
                    <div className="header-left">
                        <HardDrive size={20} className="card-icon" />
                        <h3>볼륨 사용량</h3>
                    </div>
                </div>
                <div className="disk-grid">
                    {stats?.storage?.length === 0 && <p className="no-data">볼륨 정보를 찾을 수 없습니다.</p>}
                    {stats?.storage?.map((disk, idx) => (
                        <div key={idx} className="disk-item">
                            <div className="disk-labels">
                                <span className="disk-name">{disk.mount}</span>
                                <span className="disk-stats">{(disk.used / 1024 / 1024 / 1024).toFixed(0)} GB / {(disk.size / 1024 / 1024 / 1024).toFixed(0)} GB</span>
                            </div>
                            <div className="progress-container small">
                                <div
                                    className="progress-fill"
                                    style={{
                                        width: `${disk.use}%`,
                                        backgroundColor: disk.use > 80 ? 'var(--error-color)' : 'var(--volume-color)'
                                    }}
                                />
                            </div>
                            <span className="disk-percent">{disk.use}%</span>
                        </div>
                    ))}
                </div>
            </div>

            {/* Network Widget */}
            <div className="glass-card network-card">
                <div className="card-header-simple mb-3">
                    <div className="header-left">
                        <Network size={20} className="card-icon" />
                        <h3>네트워크 (Total)</h3>
                    </div>
                </div>

                <div className="chart-wrapper" style={{ height: '200px', width: '100%' }}>
                    <ResponsiveContainer width="100%" height="100%">
                        <AreaChart data={history}>
                            <defs>
                                <linearGradient id="colorRx" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor="var(--success-color)" stopOpacity={0.8} />
                                    <stop offset="95%" stopColor="var(--success-color)" stopOpacity={0} />
                                </linearGradient>
                                <linearGradient id="colorTx" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor="var(--cpu-color)" stopOpacity={0.8} />
                                    <stop offset="95%" stopColor="var(--cpu-color)" stopOpacity={0} />
                                </linearGradient>
                            </defs>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="rgba(255,255,255,0.1)" />
                            <XAxis dataKey="time" hide />
                            <YAxis
                                width={80}
                                tickFormatter={(value) => {
                                    if (value < 1024) return `${value.toFixed(0)} B/s`;
                                    if (value < 1024 * 1024) return `${(value / 1024).toFixed(0)} KB/s`;
                                    return `${(value / 1024 / 1024).toFixed(1)} MB/s`;
                                }}
                                style={{ fontSize: '0.75rem', fill: 'var(--text-secondary)' }}
                            />
                            <Tooltip
                                contentStyle={{ background: 'var(--card-bg)', borderColor: 'var(--glass-border)', color: 'var(--text-primary)' }}
                                formatter={(value, name) => {
                                    let formatted;
                                    if (value < 1024) formatted = `${value.toFixed(0)} B/s`;
                                    else if (value < 1024 * 1024) formatted = `${(value / 1024).toFixed(1)} KB/s`;
                                    else formatted = `${(value / 1024 / 1024).toFixed(2)} MB/s`;
                                    return [formatted, name];
                                }}
                            />
                            <Area name="Download" type="monotone" dataKey="rx" stroke="var(--success-color)" fillOpacity={1} fill="url(#colorRx)" strokeWidth={2} isAnimationActive={false} />
                            <Area name="Upload" type="monotone" dataKey="tx" stroke="var(--cpu-color)" fillOpacity={1} fill="url(#colorTx)" strokeWidth={2} isAnimationActive={false} />
                        </AreaChart>
                    </ResponsiveContainer>
                </div>

                {/* Optional: Simple List below chart for current values per interface */}
                <div className="network-list" style={{ marginTop: '1rem', borderTop: '1px solid var(--glass-border)', paddingTop: '1rem' }}>
                    {stats?.network?.filter(net => !hiddenInterfaces?.includes(net.iface)).map((net, idx) => {
                        const formatSpeed = (bytes) => {
                            if (!bytes) return '0 B/s';
                            if (bytes < 1024) return `${bytes.toFixed(0)} B/s`;
                            if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB/s`;
                            return `${(bytes / 1024 / 1024).toFixed(1)} MB/s`;
                        };
                        return (
                            <div key={idx} className="network-row-simple">
                                <span className="iface-name">{net.iface}</span>
                                <div className="io-stats">
                                    <span style={{ color: 'var(--success-color)' }}>↓ {formatSpeed(net.rx_sec)}</span>
                                    <span style={{ marginLeft: '1rem', color: 'var(--cpu-color)' }}>↑ {formatSpeed(net.tx_sec)}</span>
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>

            <style>{`
        /* System Info Card Update - Fix Dark Mode Issue */
        .system-info-card {
            display: flex;
            align-items: center;
            gap: 1.5rem;
            padding: 1.5rem;
            /* Remove hardcoded background to inherit glass-card style */
        }
        .sys-icon {
            padding: 0.3rem;
            background: rgba(255,255,255,0.1); /* More subtle */
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .sys-details {
            flex: 1;
        }
        .model-text-gradient {
            font-size: 1.5rem;
            font-weight: 700;
            background: var(--brand-gradient);
            -webkit-background-clip: text;
            background-clip: text;
            -webkit-text-fill-color: transparent;
            display: inline-block;
            margin-bottom: 0.2rem;
        }
        .sys-subtitle {
            font-size: 0.9rem;
            color: var(--text-secondary);
            font-weight: 500;
            margin-top: 0.2rem;
            opacity: 0.8;
        }

        .sys-meta {
            display: flex;
            gap: 2rem;
        }
        .meta-item {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            justify-content: center;
        }
        .meta-item .label {
            font-size: 0.75rem;
            color: var(--text-secondary);
            text-transform: uppercase;
        }
        .meta-item .value {
            font-weight: 600;
            font-size: 0.95rem;
        }

        @media (max-width: 768px) {
            .sys-meta {
                display: none;
            }
        }

        /* Resource Row (CPU/Mem) */
        .resource-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }
        .card-header-simple {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }
        .header-left {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        .card-icon { color: var(--text-secondary); }
        
        .percentage-value {
            font-size: 1.5rem;
            font-weight: 700;
        }

        .progress-container {
            width: 100%;
            height: 12px;
            background: rgba(0,0,0,0.05);
            border-radius: 6px;
            overflow: hidden;
            position: relative;
        }
        .progress-fill {
            height: 100%;
            border-radius: 6px;
            transition: width 0.5s ease-out;
        }

        /* Disk Card */
        .mb-3 { margin-bottom: 1rem; }
        .disk-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1.25rem;
        }
        .disk-item {
            display: grid;
            grid-template-columns: 200px 1fr 50px;
            align-items: center;
            gap: 1rem;
        }
        .disk-labels {
            display: flex;
            flex-direction: column;
        }
        .disk-name { font-weight: 600; font-size: 0.95rem; }
        .disk-stats { font-size: 0.8rem; color: var(--text-secondary); }
        .disk-percent { 
            font-weight: 600; 
            text-align: right;
            color: var(--text-secondary);
        }
        .progress-container.small { height: 8px; }
        
        /* Network */
        .network-row-simple {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }
        .network-row-simple:last-child { border-bottom: none; }
        .io-stats { 
            font-family: monospace; 
            font-weight: 500;
            color: var(--text-secondary);
        }

        @media (max-width: 768px) {
            .resource-row { 
                grid-template-columns: 1fr; 
                gap: 1rem;
            }
            .sys-card { flex-direction: column; align-items: flex-start; }
            .sys-meta { width: 100%; justify-content: space-between; margin-top: 1rem; }
            .disk-item { grid-template-columns: 1fr; gap: 0.5rem; }
            .disk-percent { text-align: left; }
        }
      `}</style>
        </div>
    );
};

export default Dashboard;
