import { useQuery } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router'
import {
  Area,
  CartesianGrid,
  ComposedChart,
  Line,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts'
import type { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent'
import { orpc } from '@/client/orpc'
import type { DashboardSnapshot, DeviceStatus } from '@/domain/battery'

export const Route = createFileRoute('/')({
  component: Dashboard,
  errorComponent: ({ error }) => (
    <main className="flex min-h-screen items-center justify-center bg-[#09090B]">
      <div className="text-center">
        <p className="text-lg text-red-400">数据加载失败</p>
        <p className="mt-2 text-sm text-[#71717A]">{error.message}</p>
      </div>
    </main>
  ),
})

function buildChartData(soh: DashboardSnapshot['soh']) {
  const chartData: { month: string; history?: number; forecast?: number }[] = soh.history.map((h) => ({
    month: h.month,
    history: h.value,
    forecast: undefined,
  }))

  if (chartData.length > 0 && soh.forecast.length > 0) {
    // Overlap: last history point is also first forecast point
    const last = chartData[chartData.length - 1]
    if (last) {
      last.forecast = soh.forecast[0]?.value
    }
  }

  for (let i = 1; i < soh.forecast.length; i++) {
    const f = soh.forecast[i]
    if (f) {
      chartData.push({
        month: f.month,
        history: undefined,
        forecast: f.value,
      })
    }
  }

  return chartData
}

const statusColorMap: Record<DeviceStatus, string> = {
  健康: 'text-emerald-400',
  关注: 'text-amber-400',
  预警: 'text-red-400',
}

const severityColorMap: Record<DashboardSnapshot['events'][number]['severity'], string> = {
  高: 'text-red-400',
  中: 'text-amber-400',
  低: 'text-zinc-400',
}

function formatChartTooltip(value: ValueType | undefined, name: NameType | undefined) {
  const numericValue = typeof value === 'number' ? value : Number(value)

  return [
    `${Number.isFinite(numericValue) ? numericValue.toFixed(1) : (value ?? '-')}%`,
    name === 'history' ? '历史观测' : '模型预测',
  ]
}

function Dashboard() {
  const { data, error, isPending } = useQuery(orpc.battery.dashboard.queryOptions())

  if (error) {
    return (
      <main className="flex min-h-screen items-center justify-center bg-[#09090B]">
        <div className="text-center">
          <p className="text-lg text-red-400">数据加载失败</p>
          <p className="mt-2 text-sm text-[#71717A]">{error.message}</p>
        </div>
      </main>
    )
  }

  if (isPending || !data) {
    return (
      <main className="flex min-h-screen items-center justify-center bg-[#09090B]">
        <p className="text-[#71717A]">加载中…</p>
      </main>
    )
  }

  const { devices, soh, events, strategies, summary } = data
  const {
    totalDevices,
    avgSoh,
    avgSoh30d,
    avgSoh90d,
    warningCount,
    watchCount,
    healthyCount,
    batchPerformance,
    riskFactorCounts,
    firmwareHealth,
    updatedAt,
    executiveSummary,
  } = summary
  const chartData = buildChartData(soh)

  return (
    <main className="min-h-screen w-full bg-[#09090B] font-sans text-[#F4F4F5]">
      {/* Background gradient */}
      <div className="pointer-events-none fixed inset-0 z-0 flex justify-center">
        <div className="h-[800px] w-[1200px] -translate-y-1/2 rounded-full bg-teal-900/10 blur-[120px]" />
      </div>

      <div className="relative z-10 mx-auto max-w-[1400px] px-6 pb-24 pt-12 lg:px-12">
        {/* Header */}
        <header className="animate-fade-up mb-12 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
          <div className="max-w-3xl">
            <div className="mb-4 inline-flex items-center gap-2 rounded-md border border-white/10 bg-white/5 px-2.5 py-1 text-xs font-medium text-teal-400">
              智能戒指电池健康预测模型 (v2.4)
            </div>
            <h1 className="text-4xl font-light tracking-tight text-white sm:text-5xl">SoH 预测与风险洞察</h1>
          </div>
          <div className="flex flex-col items-end gap-3 text-right">
            <div className="flex items-center gap-6 text-sm">
              <div>
                <span className="text-[#71717A]">模型回测准确率 (MAE)</span>
                <span className="ml-2 font-medium tabular-nums text-teal-400">1.2%</span>
              </div>
              <div className="h-4 w-px bg-white/10" />
              <div>
                <span className="text-[#71717A]">预测命中率</span>
                <span className="ml-2 font-medium tabular-nums text-teal-400">94.5%</span>
              </div>
            </div>
            <p className="text-xs tabular-nums text-[#71717A]">数据更新时间: {updatedAt}</p>
            <Link to="/batteries" className="text-xs text-teal-400 hover:text-teal-300">
              设备电池实时状态 →
            </Link>
          </div>
        </header>

        {/* Executive Summary */}
        <section className="animate-fade-up delay-100 mb-12 rounded-xl border border-teal-900/30 bg-teal-950/10 p-6">
          <h2 className="mb-3 text-sm font-medium text-teal-400">执行摘要</h2>
          <p className="text-base leading-relaxed text-[#A1A1AA]">{executiveSummary}</p>
        </section>

        {/* Primary KPI Row */}
        <section className="animate-fade-up delay-200 mb-12 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5">
          {/* Hero KPI */}
          <article className="relative overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03] p-8 lg:col-span-2">
            <div className="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-teal-500/50 to-transparent" />
            <p className="text-sm font-medium text-[#A1A1AA]">当前平均 SoH</p>
            <div className="mt-4 flex items-baseline gap-2">
              <h2 className="text-6xl font-light tabular-nums text-white">{avgSoh.toFixed(1)}</h2>
              <span className="text-2xl text-[#71717A]">%</span>
            </div>
            <div className="mt-6 flex items-center gap-3 text-sm">
              <span className="inline-flex items-center gap-1.5 text-emerald-400">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
                基线健康
              </span>
              <span className="text-[#71717A]">|</span>
              <span className="text-[#A1A1AA]">共 {totalDevices} 台设备</span>
            </div>
          </article>

          {/* Regular KPIs */}
          <article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
            <p className="text-sm text-[#A1A1AA]">30 天预测均值</p>
            <div className="mt-3 flex items-baseline gap-1">
              <h2 className="text-4xl font-light tabular-nums text-white">{avgSoh30d.toFixed(1)}</h2>
              <span className="text-lg text-[#71717A]">%</span>
            </div>
            <div className="mt-4 flex items-center gap-1.5 text-sm">
              <span className="text-red-400">↘</span>
              <span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh30d).toFixed(1)}% 衰减</span>
            </div>
          </article>

          <article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
            <p className="text-sm text-[#A1A1AA]">90 天预测均值</p>
            <div className="mt-3 flex items-baseline gap-1">
              <h2 className="text-4xl font-light tabular-nums text-white">{avgSoh90d.toFixed(1)}</h2>
              <span className="text-lg text-[#71717A]">%</span>
            </div>
            <div className="mt-4 flex items-center gap-1.5 text-sm">
              <span className="text-red-400">↘</span>
              <span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh90d).toFixed(1)}% 衰减</span>
            </div>
          </article>

          <article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
            <p className="text-sm text-[#A1A1AA]">高风险设备</p>
            <div className="mt-3 flex items-baseline gap-1">
              <h2 className="text-4xl font-light tabular-nums text-white">{warningCount}</h2>
              <span className="text-lg text-[#71717A]">台</span>
            </div>
            <div className="mt-4 flex items-center gap-1.5 text-sm">
              <span className="text-amber-400">↗</span>
              <span className="tabular-nums text-[#A1A1AA]">
                占比 {totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
              </span>
            </div>
          </article>
        </section>

        {/* Divider */}
        <hr className="my-12 border-white/5" />

        {/* SoH Trend Chart */}
        <section className="animate-fade-up delay-300 mb-12">
          <article className="rounded-2xl border border-white/[0.06] bg-white/[0.03] p-8">
            <header className="mb-8 flex flex-wrap items-end justify-between gap-4">
              <div>
                <h3 className="text-xl font-medium text-white">SoH 衰减趋势与 90 天预测</h3>
                <p className="mt-1 text-sm text-[#A1A1AA]">基于历史 12 个月真实数据与未来 3 个月模型预测区间</p>
              </div>
              <div className="flex items-center gap-6 text-sm text-[#A1A1AA]">
                <span className="inline-flex items-center gap-2">
                  <span className="h-2 w-4 rounded-full bg-teal-400" />
                  历史观测值
                </span>
                <span className="inline-flex items-center gap-2">
                  <span className="h-2 w-4 rounded-full bg-indigo-400" />
                  模型预测值
                </span>
              </div>
            </header>

            <div className="w-full h-[320px]">
              <ResponsiveContainer width="100%" height="100%">
                <ComposedChart data={chartData} margin={{ top: 24, right: 24, bottom: 8, left: 0 }}>
                  <defs>
                    <linearGradient id="historyFill" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#2DD4BF" stopOpacity={0.15} />
                      <stop offset="100%" stopColor="#2DD4BF" stopOpacity={0} />
                    </linearGradient>
                    <linearGradient id="forecastFill" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#818CF8" stopOpacity={0.15} />
                      <stop offset="100%" stopColor="#818CF8" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid stroke="#ffffff" strokeOpacity={0.05} vertical={false} />
                  <XAxis dataKey="month" tick={{ fill: '#71717A', fontSize: 11 }} axisLine={false} tickLine={false} />
                  <YAxis
                    domain={[(min: number) => Math.floor(min) - 2, (max: number) => Math.ceil(max) + 2]}
                    tick={{ fill: '#71717A', fontSize: 11 }}
                    axisLine={false}
                    tickLine={false}
                    tickFormatter={(v: number) => `${v}%`}
                    width={48}
                  />
                  <Tooltip
                    contentStyle={{
                      backgroundColor: '#18181B',
                      border: '1px solid rgba(255,255,255,0.1)',
                      borderRadius: 8,
                      fontSize: 13,
                      color: '#F4F4F5',
                    }}
                    itemStyle={{ color: '#A1A1AA' }}
                    formatter={formatChartTooltip}
                    labelStyle={{ color: '#71717A', marginBottom: 4 }}
                  />
                  <ReferenceLine
                    y={85}
                    stroke="#F87171"
                    strokeOpacity={0.4}
                    strokeDasharray="4 4"
                    label={{
                      value: '85% 预警线',
                      fill: '#F87171',
                      fontSize: 11,
                      position: 'right',
                    }}
                  />
                  <Area
                    type="monotone"
                    dataKey="history"
                    fill="url(#historyFill)"
                    stroke="none"
                    connectNulls={false}
                    tooltipType="none"
                  />
                  <Area
                    type="monotone"
                    dataKey="forecast"
                    fill="url(#forecastFill)"
                    stroke="none"
                    connectNulls={false}
                    tooltipType="none"
                  />
                  <Line
                    type="monotone"
                    dataKey="history"
                    stroke="#2DD4BF"
                    strokeWidth={2.5}
                    dot={{
                      fill: '#09090B',
                      stroke: '#2DD4BF',
                      strokeWidth: 2,
                      r: 3,
                    }}
                    connectNulls={false}
                  />
                  <Line
                    type="monotone"
                    dataKey="forecast"
                    stroke="#818CF8"
                    strokeWidth={2.5}
                    strokeDasharray="4 4"
                    dot={{
                      fill: '#09090B',
                      stroke: '#818CF8',
                      strokeWidth: 2,
                      r: 3,
                    }}
                    connectNulls={false}
                  />
                </ComposedChart>
              </ResponsiveContainer>
            </div>
          </article>
        </section>

        {/* Two-column grid */}
        <section className="animate-fade-up delay-400 mb-12 grid grid-cols-1 gap-8 lg:grid-cols-2">
          {/* Left Column */}
          <div className="space-y-8">
            {/* Risk Distribution */}
            <div>
              <h3 className="mb-6 text-lg font-medium text-white">风险分层与结构</h3>
              <div className="space-y-5">
                <div>
                  <div className="mb-2 flex justify-between text-sm">
                    <span className="text-[#A1A1AA]">健康 (SoH &gt; 90%)</span>
                    <span className="tabular-nums text-white">
                      {healthyCount} 台{' '}
                      <span className="text-[#71717A]">
                        / {totalDevices > 0 ? ((healthyCount / totalDevices) * 100).toFixed(1) : 0}%
                      </span>
                    </span>
                  </div>
                  <div className="h-1.5 overflow-hidden rounded-full bg-white/5">
                    <div
                      className="h-full rounded-full bg-emerald-400"
                      style={{ width: `${totalDevices > 0 ? (healthyCount / totalDevices) * 100 : 0}%` }}
                    />
                  </div>
                </div>
                <div>
                  <div className="mb-2 flex justify-between text-sm">
                    <span className="text-[#A1A1AA]">关注 (85% &lt; SoH &le; 90%)</span>
                    <span className="tabular-nums text-white">
                      {watchCount} 台{' '}
                      <span className="text-[#71717A]">
                        / {totalDevices > 0 ? ((watchCount / totalDevices) * 100).toFixed(1) : 0}%
                      </span>
                    </span>
                  </div>
                  <div className="h-1.5 overflow-hidden rounded-full bg-white/5">
                    <div
                      className="h-full rounded-full bg-amber-400"
                      style={{ width: `${totalDevices > 0 ? (watchCount / totalDevices) * 100 : 0}%` }}
                    />
                  </div>
                </div>
                <div>
                  <div className="mb-2 flex justify-between text-sm">
                    <span className="text-[#A1A1AA]">预警 (SoH &le; 85%)</span>
                    <span className="tabular-nums text-white">
                      {warningCount} 台{' '}
                      <span className="text-[#71717A]">
                        / {totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
                      </span>
                    </span>
                  </div>
                  <div className="h-1.5 overflow-hidden rounded-full bg-white/5">
                    <div
                      className="h-full rounded-full bg-red-400"
                      style={{ width: `${totalDevices > 0 ? (warningCount / totalDevices) * 100 : 0}%` }}
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* Regional Performance */}
            <div>
              <h3 className="mb-6 text-lg font-medium text-white">批次健康度概览</h3>
              <div className="space-y-4">
                {batchPerformance.length > 0 ? (
                  batchPerformance.map((item) => (
                    <div key={item.batch} className="flex items-center gap-4">
                      <span className="w-20 text-sm text-[#A1A1AA]">{item.batch}</span>
                      <div className="flex-1">
                        <div className="h-1.5 overflow-hidden rounded-full bg-white/5">
                          <div className="h-full rounded-full bg-white/20" style={{ width: `${item.avgSoh}%` }} />
                        </div>
                      </div>
                      <span className="w-12 text-right text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</span>
                    </div>
                  ))
                ) : (
                  <div className="text-sm text-[#71717A]">暂无数据</div>
                )}
              </div>
            </div>
          </div>

          {/* Right Column */}
          <div className="space-y-8">
            {/* Event Timeline */}
            <div>
              <h3 className="mb-6 text-lg font-medium text-white">异常特征时间轴</h3>
              <div className="relative border-l border-white/10 pl-5">
                {events.length > 0 ? (
                  events.map((event) => (
                    <div key={event.time + event.title} className="mb-6 last:mb-0">
                      <div
                        className={`absolute -left-[4px] mt-1.5 h-2 w-2 rounded-full ${
                          event.severity === '高' ? 'bg-red-400' : 'bg-amber-400'
                        }`}
                      />
                      <div className="mb-1 flex items-center gap-3">
                        <span className="text-xs font-medium tabular-nums text-[#71717A]">{event.time}</span>
                        <span className={`text-xs ${severityColorMap[event.severity]}`}>{event.severity}风险</span>
                      </div>
                      <h4 className="text-sm font-medium text-[#F4F4F5]">{event.title}</h4>
                      <p className="mt-1 text-sm leading-relaxed text-[#A1A1AA]">{event.detail}</p>
                    </div>
                  ))
                ) : (
                  <div className="text-sm text-[#71717A]">暂无数据</div>
                )}
              </div>
            </div>

            {/* Risk Factor Frequency */}
            <div>
              <h3 className="mb-6 text-lg font-medium text-white">主要风险因子分布</h3>
              <div className="flex flex-wrap gap-2">
                {riskFactorCounts.length > 0 ? (
                  riskFactorCounts.map((item) => (
                    <div
                      key={item.factor}
                      className="flex items-center gap-2 rounded-md border border-white/5 bg-white/[0.02] px-3 py-1.5 text-sm"
                    >
                      <span className="text-[#A1A1AA]">{item.factor}</span>
                      <span className="rounded bg-white/10 px-1.5 py-0.5 text-xs tabular-nums text-white">
                        {item.count}
                      </span>
                    </div>
                  ))
                ) : (
                  <div className="text-sm text-[#71717A]">暂无数据</div>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* Divider */}
        <hr className="my-12 border-white/5" />

        {/* Device Table */}
        <section className="animate-fade-up delay-500 mb-12">
          <div className="mb-6 flex items-end justify-between">
            <div>
              <h3 className="text-xl font-medium text-white">高风险设备清单与预测明细</h3>
              <p className="mt-1 text-sm text-[#A1A1AA]">按综合风险评分排序，展示未来 30/60/90 天衰减预测</p>
            </div>
          </div>
          <div className="overflow-x-auto rounded-xl border border-white/[0.06] bg-white/[0.02]">
            <table className="w-full min-w-[1000px] border-collapse text-left text-sm">
              <thead>
                <tr className="border-b border-white/10 bg-white/[0.02] text-[#A1A1AA]">
                  <th className="px-6 py-4 font-medium">设备标识</th>
                  <th className="px-6 py-4 font-medium">生产批次</th>
                  <th className="px-6 py-4 font-medium">当前 SoH</th>
                  <th className="px-6 py-4 font-medium">30天预测</th>
                  <th className="px-6 py-4 font-medium">90天预测</th>
                  <th className="px-6 py-4 font-medium">风险评分</th>
                  <th className="px-6 py-4 font-medium">状态</th>
                  <th className="px-6 py-4 font-medium">主要风险因子</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {devices.length > 0 ? (
                  devices
                    .slice()
                    .sort((a, b) => b.riskScore - a.riskScore)
                    .map((unit) => (
                      <tr key={unit.id} className="transition-colors hover:bg-white/[0.04]">
                        <td className="px-6 py-4 font-medium text-white">{unit.id}</td>
                        <td className="px-6 py-4 text-[#A1A1AA]">{unit.batch}</td>
                        <td className="px-6 py-4 tabular-nums text-white">{unit.soh.toFixed(1)}%</td>
                        <td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh30d.toFixed(1)}%</td>
                        <td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh90d.toFixed(1)}%</td>
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2">
                            <div className="h-1.5 w-12 overflow-hidden rounded-full bg-white/5">
                              <div
                                className={`h-full rounded-full ${
                                  unit.riskScore >= 75
                                    ? 'bg-red-400'
                                    : unit.riskScore >= 45
                                      ? 'bg-amber-400'
                                      : 'bg-emerald-400'
                                }`}
                                style={{ width: `${unit.riskScore}%` }}
                              />
                            </div>
                            <span className="tabular-nums text-white">{unit.riskScore}</span>
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <span className={statusColorMap[unit.status]}>{unit.status}</span>
                        </td>
                        <td className="px-6 py-4">
                          <div className="flex flex-wrap gap-1.5">
                            {unit.riskFactors.length > 0 ? (
                              unit.riskFactors.map((factor) => (
                                <span key={factor} className="text-[#A1A1AA]">
                                  {factor}
                                  {factor !== unit.riskFactors[unit.riskFactors.length - 1] && '、'}
                                </span>
                              ))
                            ) : (
                              <span className="text-[#71717A]">-</span>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))
                ) : (
                  <tr>
                    <td colSpan={8} className="px-6 py-8 text-center text-[#71717A]">
                      暂无设备数据
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </section>

        {/* Bottom Row */}
        <section className="animate-fade-up delay-500 grid grid-cols-1 gap-8 lg:grid-cols-3">
          {/* Strategy Cards */}
          <div className="lg:col-span-2">
            <h3 className="mb-6 text-lg font-medium text-white">模型驱动的维护策略建议</h3>
            <div className="grid gap-4 sm:grid-cols-2">
              {strategies.length > 0 ? (
                strategies.map((item, index) => (
                  <div
                    key={item.name}
                    className="relative overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02] p-5"
                  >
                    <div
                      className={`absolute bottom-0 left-0 top-0 w-1 ${index === 0 ? 'bg-red-400' : index === 1 ? 'bg-amber-400' : 'bg-teal-400'}`}
                    />
                    <h4 className="font-medium text-white">{item.name}</h4>
                    <p className="mt-2 text-sm text-[#A1A1AA]">{item.impact}</p>
                    <div className="mt-4 flex flex-wrap gap-4 text-xs text-[#71717A]">
                      <span>范围: {item.scope}</span>
                      <span>时效: {item.eta}</span>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-sm text-[#71717A] col-span-2">暂无策略建议</div>
              )}
            </div>
          </div>

          {/* Firmware Comparison */}
          <div>
            <h3 className="mb-6 text-lg font-medium text-white">固件版本健康度对比</h3>
            <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-5">
              <div className="space-y-4">
                {firmwareHealth.length > 0 ? (
                  firmwareHealth.map((item) => (
                    <div key={item.firmware} className="flex items-center justify-between">
                      <div>
                        <div className="text-sm font-medium text-white">{item.firmware}</div>
                        <div className="text-xs text-[#71717A]">{item.count} 台设备</div>
                      </div>
                      <div className="text-right">
                        <div className="text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</div>
                        <div className="text-xs text-[#71717A]">平均 SoH</div>
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="text-sm text-[#71717A]">暂无数据</div>
                )}
              </div>
            </div>
          </div>
        </section>
      </div>
    </main>
  )
}
