import React, { useState } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { formatBytes } from '../utils/format';

/**
 * 네트워크 트래픽 차트 컴포넌트 (글래스모피즘 버전)
 * 다운로드/업로드 속도 이력을 프리미엄 그래프로 표시합니다.
 */
export default function NetworkChart({ data }) {
  const [visible, setVisible] = useState({
    recv: true,
    sent: true
  });

  const handleLegendClick = (e) => {
    const { dataKey } = e;
    // dataKey가 net_recv/net_sent이므로 매핑
    const key = dataKey === 'net_recv' ? 'recv' : 'sent';
    setVisible({ ...visible, [key]: !visible[key] });
  };

  // 커스텀 툴팁 스타일
  const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length) {
      const [h, m, s] = label.split(':');
      return (
        <div className="bg-slate-900/95 backdrop-blur-xl border border-white/10 rounded-xl p-3 shadow-xl">
          <p className="text-slate-400 text-xs mb-2">{`${parseInt(h)}시 ${parseInt(m)}분 ${parseInt(s)}초`}</p>
          {payload.map((entry, index) => (
            <div key={index} className="flex items-center gap-2 text-sm">
              <div className="w-2 h-2 rounded-full" style={{ backgroundColor: entry.color }} />
              <span className="text-slate-300">{entry.name}:</span>
              <span className="font-bold text-white">{formatBytes(entry.value)}</span>
            </div>
          ))}
        </div>
      );
    }
    return null;
  };

  return (
    <div className="relative overflow-hidden rounded-2xl p-6 mt-6
      bg-white/[0.02] backdrop-blur-xl border border-white/[0.06]
      shadow-[inset_0_1px_0_0_rgba(255,255,255,0.03)]">
      
      {/* 상단 그라디언트 라인 */}
      <div className="absolute top-0 left-0 right-0 h-[1px] 
        bg-gradient-to-r from-transparent via-white/10 to-transparent" />

      <h3 className="text-lg font-bold mb-4 bg-gradient-to-r from-slate-100 to-slate-300 
        bg-clip-text text-transparent">네트워크 트래픽</h3>
      
      <div className="h-[300px] w-full">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={data} margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
            <defs>
              {/* 다운로드 그라디언트 (청록색) */}
              <linearGradient id="colorRecv" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#0ea5e9" stopOpacity={0.4}/>
                <stop offset="50%" stopColor="#0ea5e9" stopOpacity={0.1}/>
                <stop offset="95%" stopColor="#0ea5e9" stopOpacity={0}/>
              </linearGradient>
              {/* 업로드 그라디언트 (오렌지) */}
              <linearGradient id="colorSent" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#f97316" stopOpacity={0.4}/>
                <stop offset="50%" stopColor="#f97316" stopOpacity={0.1}/>
                <stop offset="95%" stopColor="#f97316" stopOpacity={0}/>
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" stroke="#334155" opacity={0.3} vertical={false} />
            <XAxis 
              dataKey="time" 
              interval={0} 
              stroke="#64748b" 
              fontSize={11} 
              tickLine={false}
              axisLine={false}
            />
            <YAxis 
              stroke="#64748b" 
              fontSize={11} 
              tickLine={false}
              axisLine={false}
              tickFormatter={(value) => formatBytes(value)}
            />
            <Tooltip content={<CustomTooltip />} />
            <Legend 
              onClick={handleLegendClick} 
              wrapperStyle={{ cursor: 'pointer', paddingTop: '10px' }}
              formatter={(value) => <span className="text-slate-400 hover:text-white transition-colors">{value}</span>}
            />
            <Area 
              type="monotone" 
              dataKey="net_recv" 
              name="다운로드"
              stroke="#0ea5e9" 
              strokeWidth={2}
              fillOpacity={1} 
              fill="url(#colorRecv)" 
              hide={!visible.recv}
              isAnimationActive={false}
            />
            <Area 
              type="monotone" 
              dataKey="net_sent" 
              name="업로드"
              stroke="#f97316" 
              strokeWidth={2}
              fillOpacity={1} 
              fill="url(#colorSent)" 
              hide={!visible.sent}
              isAnimationActive={false}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>

      {/* 배경 데코레이션 */}
      <div className="absolute -right-10 top-1/3 w-40 h-40 
        bg-cyan-500/5 rounded-full blur-3xl pointer-events-none" />
      <div className="absolute -left-10 bottom-10 w-32 h-32 
        bg-orange-500/5 rounded-full blur-3xl pointer-events-none" />
    </div>
  );
}
