import { useMemo } from 'react';

// 简易折线图组件
export default function UptimeChart({ data, height = 120, showLabels = true }) {
  // 处理数据
  const chartData = useMemo(() => {
    if (!data || data.length === 0) {
      // 生成模拟数据点
      return Array(24).fill(null).map((_, i) => ({
        hour: i,
        uptime: null,
        avgLatency: 0,
      }));
    }
    
    // 按时间排序
    const sorted = [...data].sort((a, b) => 
      new Date(a.hour).getTime() - new Date(b.hour).getTime()
    );
    
    return sorted.map(item => ({
      hour: new Date(item.hour).getHours(),
      uptime: item.uptime,
      avgLatency: item.avg_latency,
    }));
  }, [data]);

  // 计算图表尺寸
  const padding = { top: 20, right: 20, bottom: showLabels ? 30 : 10, left: showLabels ? 40 : 10 };
  const width = 400;
  const chartWidth = width - padding.left - padding.right;
  const chartHeight = height - padding.top - padding.bottom;

  // 生成路径
  const pathData = useMemo(() => {
    const validPoints = chartData.filter(d => d.uptime !== null);
    if (validPoints.length === 0) return '';
    
    const xStep = chartWidth / (chartData.length - 1 || 1);
    
    let path = '';
    let lastValidIndex = -1;
    
    chartData.forEach((d, i) => {
      if (d.uptime !== null) {
        const x = i * xStep;
        const y = chartHeight - (d.uptime / 100 * chartHeight);
        
        if (lastValidIndex === -1) {
          path += `M ${x} ${y}`;
        } else {
          path += ` L ${x} ${y}`;
        }
        lastValidIndex = i;
      }
    });
    
    return path;
  }, [chartData, chartWidth, chartHeight]);

  // 生成填充区域
  const areaPath = useMemo(() => {
    if (!pathData) return '';
    
    const validPoints = chartData.filter(d => d.uptime !== null);
    if (validPoints.length === 0) return '';
    
    const xStep = chartWidth / (chartData.length - 1 || 1);
    const firstValidIndex = chartData.findIndex(d => d.uptime !== null);
    const lastValidIndex = chartData.length - 1 - [...chartData].reverse().findIndex(d => d.uptime !== null);
    
    const startX = firstValidIndex * xStep;
    const endX = lastValidIndex * xStep;
    
    return `${pathData} L ${endX} ${chartHeight} L ${startX} ${chartHeight} Z`;
  }, [pathData, chartData, chartWidth, chartHeight]);

  // 获取颜色
  const getColor = (uptime) => {
    if (uptime >= 99) return '#10b981'; // emerald-500
    if (uptime >= 95) return '#34d399'; // emerald-400
    if (uptime >= 90) return '#fbbf24'; // amber-400
    return '#ef4444'; // red-500
  };

  // 计算平均可用率
  const avgUptime = useMemo(() => {
    const validPoints = chartData.filter(d => d.uptime !== null);
    if (validPoints.length === 0) return null;
    return validPoints.reduce((sum, d) => sum + d.uptime, 0) / validPoints.length;
  }, [chartData]);

  const color = avgUptime !== null ? getColor(avgUptime) : '#d1d5db';

  return (
    <div className="w-full">
      <svg 
        viewBox={`0 0 ${width} ${height}`}
        className="w-full h-auto"
        preserveAspectRatio="xMidYMid meet"
      >
        <defs>
          <linearGradient id="uptimeGradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stopColor={color} stopOpacity="0.3" />
            <stop offset="100%" stopColor={color} stopOpacity="0.05" />
          </linearGradient>
        </defs>
        
        <g transform={`translate(${padding.left}, ${padding.top})`}>
          {/* 网格线 */}
          {[0, 25, 50, 75, 100].map(v => (
            <g key={v}>
              <line 
                x1={0} 
                y1={chartHeight - (v / 100 * chartHeight)}
                x2={chartWidth}
                y2={chartHeight - (v / 100 * chartHeight)}
                stroke="#e5e7eb"
                strokeDasharray="4 2"
              />
              {showLabels && (
                <text
                  x={-8}
                  y={chartHeight - (v / 100 * chartHeight) + 4}
                  fill="#9ca3af"
                  fontSize="10"
                  textAnchor="end"
                >
                  {v}%
                </text>
              )}
            </g>
          ))}
          
          {/* 填充区域 */}
          {areaPath && (
            <path
              d={areaPath}
              fill="url(#uptimeGradient)"
            />
          )}
          
          {/* 折线 */}
          {pathData && (
            <path
              d={pathData}
              fill="none"
              stroke={color}
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          )}
          
          {/* 数据点 */}
          {chartData.map((d, i) => {
            if (d.uptime === null) return null;
            const xStep = chartWidth / (chartData.length - 1 || 1);
            const x = i * xStep;
            const y = chartHeight - (d.uptime / 100 * chartHeight);
            return (
              <circle
                key={i}
                cx={x}
                cy={y}
                r="3"
                fill="white"
                stroke={getColor(d.uptime)}
                strokeWidth="2"
              />
            );
          })}
          
          {/* X轴时间标签 */}
          {showLabels && chartData.length > 0 && (
            <>
              {[0, Math.floor(chartData.length / 2), chartData.length - 1].map(i => {
                if (i >= chartData.length) return null;
                const xStep = chartWidth / (chartData.length - 1 || 1);
                return (
                  <text
                    key={i}
                    x={i * xStep}
                    y={chartHeight + 20}
                    fill="#9ca3af"
                    fontSize="10"
                    textAnchor="middle"
                  >
                    {chartData[i]?.hour || 0}:00
                  </text>
                );
              })}
            </>
          )}
        </g>
        
        {/* 无数据提示 */}
        {!pathData && (
          <text
            x={width / 2}
            y={height / 2}
            fill="#9ca3af"
            fontSize="12"
            textAnchor="middle"
          >
            暂无数据
          </text>
        )}
      </svg>
    </div>
  );
}
