'use client'

/**
 * GlobalPulseChart - 全局脈搏統計圖
 * ==================================
 * Phase 7: 視覺主權重構
 *
 * Nothing.tech 設計語言:
 * - 白玻璃層次 (bg-white/70 backdrop-blur)
 * - 極簡配色 (白、灰、點陣紅)
 * - 無網格線，僅保留關鍵數據
 *
 * Features:
 * - 4 個核心指標卡片 (RPS, Error Rate, P99, AI Success)
 * - Sparkline 趨勢圖
 * - 即時更新動畫
 */

import { useMemo } from 'react'
import {
  Area,
  AreaChart,
  ResponsiveContainer,
} from 'recharts'
import { cn } from '@/lib/utils'
import { useTranslations } from 'next-intl'

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

export interface PulseMetric {
  label: string
  value: number | string
  unit?: string
  trend: number[] // sparkline data
  status: 'healthy' | 'warning' | 'critical'
}

export interface GlobalPulseChartProps {
  metrics: PulseMetric[]
  className?: string
}

// =============================================================================
// Status Colors (Nothing.tech palette)
// =============================================================================

const statusConfig = {
  healthy: {
    bg: 'bg-nothing-gray-50',
    border: 'border-nothing-gray-200',
    dot: 'bg-green-500',
    stroke: '#22c55e',
    fill: 'rgba(34,197,94,0.1)',
  },
  warning: {
    bg: 'bg-amber-50/50',
    border: 'border-amber-200/50',
    dot: 'bg-amber-500',
    stroke: '#f59e0b',
    fill: 'rgba(245,158,11,0.1)',
  },
  critical: {
    bg: 'bg-red-50/50',
    border: 'border-red-200/50',
    dot: 'bg-nothing-red',
    stroke: '#ef4444',
    fill: 'rgba(239,68,68,0.1)',
  },
}

// =============================================================================
// Sparkline Component
// =============================================================================

interface SparklineProps {
  data: number[]
  status: 'healthy' | 'warning' | 'critical'
}

function Sparkline({ data, status }: SparklineProps) {
  const config = statusConfig[status]
  const chartData = useMemo(
    () => data.map((value, index) => ({ index, value })),
    [data]
  )

  return (
    <div className="h-8 w-full" style={{ minWidth: 80, minHeight: 32 }}>
      <ResponsiveContainer width="100%" height={32}>
        <AreaChart data={chartData} margin={{ top: 2, right: 0, left: 0, bottom: 2 }}>
          <Area
            type="monotone"
            dataKey="value"
            stroke={config.stroke}
            strokeWidth={1.5}
            fill={config.fill}
            animationDuration={300}
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  )
}

// =============================================================================
// Metric Card Component
// =============================================================================

interface MetricCardProps {
  metric: PulseMetric
}

function MetricCard({ metric }: MetricCardProps) {
  const config = statusConfig[metric.status]

  return (
    <div
      className={cn(
        'relative p-6 rounded-sm border transition-all duration-200',
        'bg-white/70 backdrop-blur-[16px]',
        config.border,
        'hover:shadow-[0_4px_24px_rgba(0,0,0,0.06)]',
        'hover:-translate-y-0.5'
      )}
    >
      {/* Status Indicator */}
      <div className="absolute top-6 right-6">
        <div className={cn('w-2 h-2 rounded-full', config.dot)} />
      </div>

      {/* Label */}
      <p className="text-xs font-medium text-ink-secondary uppercase tracking-wider mb-2">
        {metric.label}
      </p>

      {/* Value - Dot Matrix Display (靈魂注入) */}
      <p className="dot-matrix-display">
        {metric.value}
        {metric.unit && (
          <span className="text-base font-mono font-normal text-ink-secondary ml-2">
            {metric.unit}
          </span>
        )}
      </p>

      {/* Sparkline */}
      <div className="mt-4">
        <Sparkline data={metric.trend} status={metric.status} />
      </div>
    </div>
  )
}

// =============================================================================
// Main Component
// =============================================================================

export function GlobalPulseChart({ metrics, className }: GlobalPulseChartProps) {
  const t = useTranslations('dashboard')

  return (
    <div className={cn('w-full', className)}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-heading font-semibold text-nothing-gray-900">
          {t('globalPulse')}
        </h2>
        <div className="flex items-center gap-2 text-xs text-nothing-gray-500">
          <div className="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse" />
          <span>{t('liveUpdates')}</span>
        </div>
      </div>

      {/* Metrics Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {metrics.map((metric, index) => (
          <MetricCard key={index} metric={metric} />
        ))}
      </div>
    </div>
  )
}

// =============================================================================
// Default Export with Demo Data
// =============================================================================

export function GlobalPulseChartDemo() {
  const demoMetrics: PulseMetric[] = [
    {
      label: 'RPS',
      value: 1247,
      unit: 'req/s',
      trend: [120, 135, 128, 142, 138, 145, 152, 148, 156, 160],
      status: 'healthy',
    },
    {
      label: 'Error Rate',
      value: '0.12',
      unit: '%',
      trend: [0.1, 0.15, 0.08, 0.12, 0.09, 0.11, 0.14, 0.1, 0.12, 0.12],
      status: 'healthy',
    },
    {
      label: 'P99 Latency',
      value: 245,
      unit: 'ms',
      trend: [220, 235, 248, 242, 255, 238, 252, 248, 245, 245],
      status: 'warning',
    },
    {
      label: 'AI Success',
      value: '98.5',
      unit: '%',
      trend: [97, 98, 99, 98, 97, 99, 98, 99, 98, 98.5],
      status: 'healthy',
    },
  ]

  return <GlobalPulseChart metrics={demoMetrics} />
}
