import React, { useState, useEffect, useMemo } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { History as HistoryIcon, Clock, Loader2 } from 'lucide-react';

const History = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [timeRange, setTimeRange] = useState('24h'); // '1h', '6h', '12h', '24h'

    useEffect(() => {
        const fetchHistory = async () => {
            try {
                const response = await fetch('/api/history');
                if (!response.ok) throw new Error('Failed to fetch history');
                const result = await response.json();
                setData(result);
                setLoading(false);
            } catch (err) {
                console.error('History fetch error:', err);
                setError('Failed to load history data');
                setLoading(false);
            }
        };

        fetchHistory();
        const interval = setInterval(fetchHistory, 60000); // 1 min update
        return () => clearInterval(interval);
    }, []);

    const filteredData = useMemo(() => {
        if (!data.length) return [];
        const now = Date.now();
        const ranges = {
            '1h': 60 * 60 * 1000,
            '6h': 6 * 60 * 60 * 1000,
            '12h': 12 * 60 * 60 * 1000,
            '24h': 24 * 60 * 60 * 1000,
            '7d': 7 * 24 * 60 * 60 * 1000, // Add 7d support if retention allows
        };
        const rangeMs = ranges[timeRange] || ranges['24h'];
        const cutoff = now - rangeMs;

        return data
            .filter(item => item.timestamp >= cutoff)
            .map(item => ({
                ...item,
                rx: item.network ? item.network.rx : 0,
                tx: item.network ? item.network.tx : 0,
                time: new Date(item.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            }));
    }, [data, timeRange]);

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

    const formatBytes = (bytes) => {
        if (bytes === 0) return '0 B/s';
        const k = 1024;
        const sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    const CustomTooltip = ({ active, payload, label, type }) => {
        if (active && payload && payload.length) {
            return (
                <div className="custom-tooltip" style={{ background: 'var(--card-bg)', border: '1px solid var(--glass-border)', padding: '10px', borderRadius: '8px' }}>
                    <p style={{ margin: '0 0 5px 0', fontWeight: 'bold', fontSize: '0.9rem' }}>{label}</p>
                    {payload.map((entry, index) => (
                        <p key={index} style={{ margin: 0, color: entry.color, fontSize: '0.85rem' }}>
                            {entry.name}: {type === 'network' ? formatBytes(entry.value) : `${entry.value}%`}
                        </p>
                    ))}
                </div>
            );
        }
        return null;
    };

    return (
        <div className="dashboard-container">
            <div className="glass-card full-width">
                <div className="card-header-simple mb-3 history-header">
                    <div className="header-left">
                        <HistoryIcon size={24} className="card-icon" style={{ color: 'var(--accent-color)' }} />
                        <h3>시스템 히스토리</h3>
                    </div>
                    <div className="range-controls">
                        {['1h', '6h', '12h', '24h', '7d'].map(range => (
                            <button
                                key={range}
                                className={`range-btn ${timeRange === range ? 'active' : ''}`}
                                onClick={() => setTimeRange(range)}
                            >
                                {range}
                            </button>
                        ))}
                    </div>
                </div>

                {error ? (
                    <div className="error-message">{error}</div>
                ) : (
                    <div className="charts-container">
                        <div className="chart-section">
                            <h4 className="chart-title"><span className="dot cpu"></span> CPU 사용량</h4>
                            <div style={{ width: '100%', height: 300 }}>
                                <ResponsiveContainer>
                                    <AreaChart data={filteredData}>
                                        <defs>
                                            <linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="#3182ce" stopOpacity={0.3} />
                                                <stop offset="95%" stopColor="#3182ce" stopOpacity={0} />
                                            </linearGradient>
                                        </defs>
                                        <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" vertical={false} />
                                        <XAxis dataKey="time" stroke="var(--text-secondary)" tick={{ fill: 'var(--text-secondary)', fontSize: 12 }} minTickGap={30} />
                                        <YAxis stroke="var(--text-secondary)" tick={{ fill: 'var(--text-secondary)', fontSize: 12 }} domain={[0, 100]} />
                                        <Tooltip content={<CustomTooltip />} />
                                        <Area type="monotone" dataKey="cpu" name="CPU" stroke="#3182ce" fillOpacity={1} fill="url(#colorCpu)" strokeWidth={2} />
                                    </AreaChart>
                                </ResponsiveContainer>
                            </div>
                        </div>

                        <div className="chart-section">
                            <h4 className="chart-title"><span className="dot mem"></span> 메모리 사용량</h4>
                            <div style={{ width: '100%', height: 300 }}>
                                <ResponsiveContainer>
                                    <AreaChart data={filteredData}>
                                        <defs>
                                            <linearGradient id="colorMem" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="#38a169" stopOpacity={0.3} />
                                                <stop offset="95%" stopColor="#38a169" stopOpacity={0} />
                                            </linearGradient>
                                        </defs>
                                        <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" vertical={false} />
                                        <XAxis dataKey="time" stroke="var(--text-secondary)" tick={{ fill: 'var(--text-secondary)', fontSize: 12 }} minTickGap={30} />
                                        <YAxis stroke="var(--text-secondary)" tick={{ fill: 'var(--text-secondary)', fontSize: 12 }} domain={[0, 100]} />
                                        <Tooltip content={<CustomTooltip />} />
                                        <Area type="monotone" dataKey="memory" name="Memory" stroke="#38a169" fillOpacity={1} fill="url(#colorMem)" strokeWidth={2} />
                                    </AreaChart>
                                </ResponsiveContainer>
                            </div>
                        </div>

                        <div className="chart-section">
                            <h4 className="chart-title">
                                <span className="dot" style={{ background: 'var(--success-color)' }}></span> Download
                                <span className="dot" style={{ background: 'var(--cpu-color)', marginLeft: '10px' }}></span> Upload
                            </h4>
                            <div style={{ width: '100%', height: 300 }}>
                                <ResponsiveContainer>
                                    <AreaChart data={filteredData}>
                                        <defs>
                                            <linearGradient id="colorRx" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="var(--success-color)" stopOpacity={0.3} />
                                                <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.3} />
                                                <stop offset="95%" stopColor="var(--cpu-color)" stopOpacity={0} />
                                            </linearGradient>
                                        </defs>
                                        <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" vertical={false} />
                                        <XAxis dataKey="time" stroke="var(--text-secondary)" tick={{ fill: 'var(--text-secondary)', fontSize: 12 }} minTickGap={30} />
                                        <YAxis
                                            stroke="var(--text-secondary)"
                                            tick={{ fill: 'var(--text-secondary)', fontSize: 12 }}
                                            tickFormatter={(val) => {
                                                if (val === 0) return '0 B/s';
                                                if (val < 1024) return `${val.toFixed(0)} B/s`;
                                                if (val < 1024 * 1024) return `${(val / 1024).toFixed(0)} KB/s`;
                                                return `${(val / 1024 / 1024).toFixed(1)} MB/s`;
                                            }}
                                        />
                                        <Tooltip content={<CustomTooltip type="network" />} />
                                        <Area type="monotone" dataKey="rx" name="Download" stroke="var(--success-color)" fillOpacity={1} fill="url(#colorRx)" strokeWidth={2} />
                                        <Area type="monotone" dataKey="tx" name="Upload" stroke="var(--cpu-color)" fillOpacity={1} fill="url(#colorTx)" strokeWidth={2} />
                                    </AreaChart>
                                </ResponsiveContainer>
                            </div>
                        </div>
                    </div>
                )}
            </div>

            <style>{`
                .full-width { width: 100%; padding: 2rem; }
                .dashboard-container {
                    display: flex;
                    flex-direction: column;
                    gap: 1.5rem;
                    width: 100%;
                    max-width: 1280px;
                    margin: 0 auto;
                    padding: 0 1rem;
                }
                .history-header {
                    display: flex;
                    justify-content: space-between;
                    flex-wrap: wrap;
                    gap: 1rem;
                }
                .range-controls {
                    display: flex;
                    gap: 0.5rem;
                    background: rgba(0,0,0,0.2);
                    padding: 4px;
                    border-radius: 8px;
                }
                .range-btn {
                    background: transparent;
                    border: none;
                    color: var(--text-secondary);
                    padding: 6px 12px;
                    border-radius: 6px;
                    font-size: 0.85rem;
                    cursor: pointer;
                    transition: all 0.2s;
                    font-weight: 500;
                }
                .range-btn:hover { color: var(--text-primary); background: rgba(255,255,255,0.05); }
                .range-btn.active {
                    background: var(--accent-color);
                    color: white;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
                }
                .charts-container {
                    display: flex;
                    flex-direction: column;
                    gap: 3rem;
                    margin-top: 2rem;
                }
                .chart-title {
                    margin-bottom: 1rem;
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                    font-size: 1.1rem;
                    opacity: 0.9;
                }
                .dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
                .dot.cpu { background: #3182ce; }
                .dot.mem { background: #38a169; }
                
                @media (max-width: 768px) {
                    .full-width { padding: 1rem; }
                }
            `}</style>
        </div>
    );
};

export default History;
