'use client'

/**
 * TimeSeriesChart - Nothing.tech 風格時間序列圖
 * =============================================
 * Phase 7: 視覺主權重構
 *
 * Features:
 * - SignOz Gold Metrics 時間序列展示
 * - 極簡設計 (無網格線、漸層填充)
 * - 響應式自適應
 * - i18n 支援 (zh-TW/en)
 */

import { useMemo } from 'react'
import {
  Area,
  AreaChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts'
import { cn } from '@/lib/utils'

// =============================================================================
// Types
// =============================================================================

export interface TimeSeriesDataPoint {
  timestamp: number | string
  value: number
  label?: string
}

export interface TimeSeriesChartProps {
  /** 數據點陣列 */
  data: TimeSeriesDataPoint[]
  /** 圖表高度 (px) */
  height?: number
  /** 顏色主題 */
  color?: 'primary' | 'success' | 'warning' | 'error'
  /** Y 軸單位 (e.g., 'ms', '%', 'req/s') */
  unit?: string
  /** 是否顯示 Y 軸 */
  showYAxis?: boolean
  /** 是否顯示漸層填充 */
  showGradient?: boolean
  /** 自訂 className */
  className?: string
  /** 無障礙標籤 */
  'aria-label'?: string
}

// =============================================================================
// Color Mapping
// =============================================================================

const colorMap = {
  primary: {
    stroke: '#8b5cf6', // status-thinking (purple)
    fill: 'url(#gradient-primary)',
    gradient: ['rgba(139,92,246,0.3)', 'rgba(139,92,246,0)'],
  },
  success: {
    stroke: '#22c55e', // green-500
    fill: 'url(#gradient-success)',
    gradient: ['rgba(34,197,94,0.3)', 'rgba(34,197,94,0)'],
  },
  warning: {
    stroke: '#f59e0b', // amber-500
    fill: 'url(#gradient-warning)',
    gradient: ['rgba(245,158,11,0.3)', 'rgba(245,158,11,0)'],
  },
  error: {
    stroke: '#ef4444', // red-500
    fill: 'url(#gradient-error)',
    gradient: ['rgba(239,68,68,0.3)', 'rgba(239,68,68,0)'],
  },
}

// =============================================================================
// Custom Tooltip
// =============================================================================

interface CustomTooltipProps {
  active?: boolean
  payload?: Array<{ value: number; payload: TimeSeriesDataPoint }>
  unit?: string
}

function CustomTooltip({ active, payload, unit }: CustomTooltipProps) {
  if (!active || !payload || payload.length === 0) return null

  const data = payload[0]
  const time = data.payload.label || new Date(data.payload.timestamp).toLocaleTimeString()

  return (
    <div className="bg-nothing-gray-900/95 backdrop-blur-sm px-3 py-2 rounded-lg border border-nothing-gray-700">
      <p className="text-nothing-gray-400 text-xs mb-1">{time}</p>
      <p className="text-white font-body text-sm font-semibold">
        {data.value.toFixed(2)}{unit && ` ${unit}`}
      </p>
    </div>
  )
}

// =============================================================================
// Component
// =============================================================================

export function TimeSeriesChart({
  data,
  height = 120,
  color = 'primary',
  unit,
  showYAxis = false,
  showGradient = true,
  className,
  'aria-label': ariaLabel,
}: TimeSeriesChartProps) {
  const colorConfig = colorMap[color]

  // Format timestamp for X-axis
  const formattedData = useMemo(() => {
    return data.map(point => ({
      ...point,
      label: point.label || new Date(point.timestamp).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
      }),
    }))
  }, [data])

  return (
    <div
      className={cn('w-full', className)}
      style={{ height }}
      role="img"
      aria-label={ariaLabel || 'Time series chart'}
    >
      <ResponsiveContainer width="100%" height="100%">
        <AreaChart
          data={formattedData}
          margin={{ top: 4, right: 4, left: showYAxis ? 32 : 4, bottom: 4 }}
        >
          {/* Gradient Definitions */}
          <defs>
            <linearGradient id={`gradient-${color}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={colorConfig.gradient[0]} />
              <stop offset="100%" stopColor={colorConfig.gradient[1]} />
            </linearGradient>
          </defs>

          {/* X Axis - Hidden but provides data */}
          <XAxis
            dataKey="label"
            axisLine={false}
            tickLine={false}
            tick={false}
            hide
          />

          {/* Y Axis - Optional */}
          {showYAxis && (
            <YAxis
              axisLine={false}
              tickLine={false}
              tick={{ fill: '#6b7280', fontSize: 10, fontFamily: 'var(--font-mono)' }}
              width={28}
              tickFormatter={(value) => `${value}${unit ? unit : ''}`}
            />
          )}

          {/* Tooltip */}
          <Tooltip
            content={<CustomTooltip unit={unit} />}
            cursor={{ stroke: colorConfig.stroke, strokeWidth: 1, strokeDasharray: '4 4' }}
          />

          {/* Area Chart */}
          <Area
            type="monotone"
            dataKey="value"
            stroke={colorConfig.stroke}
            strokeWidth={2}
            fill={showGradient ? colorConfig.fill : 'transparent'}
            animationDuration={300}
            animationEasing="ease-out"
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  )
}
