// Overview / dashboard home: hero stats + live activity feed + chart.

import { useQuery } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { Activity, Cpu, Radio, Server, TrendingUp } from 'lucide-react'
import { Area, AreaChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
import { format, formatDistanceToNow } from 'date-fns'
import { api } from '../lib/api'
import { subscribeSSE } from '../lib/sse'
import { Card, FadeIn, Pill, Stat } from '../components/ui'
import type { RouterEvent } from '../lib/types'

export function OverviewPage() {
  const { data: health } = useQuery({ queryKey: ['health'], queryFn: api.health, refetchInterval: 10_000 })
  const { data: routers } = useQuery({ queryKey: ['routers'], queryFn: api.routers, refetchInterval: 5_000 })
  const { data: metrics } = useQuery({ queryKey: ['metrics'], queryFn: () => api.metrics('1h'), refetchInterval: 15_000 })
  const { data: alerts } = useQuery({ queryKey: ['alerts', 'overview'], queryFn: () => api.alerts({ unack: true, limit: 5 }), refetchInterval: 30_000 })

  // Live event feed
  const [live, setLive] = useState<RouterEvent[]>([])
  useEffect(() => {
    return subscribeSSE((type, payload) => {
      if (type === 'event') {
        setLive((prev) => [payload as RouterEvent, ...prev].slice(0, 50))
      }
    })
  }, [])

  const onlineCount = routers?.routers.filter((r) => r.online).length ?? 0
  const totalRouters = routers?.routers.length ?? 0
  const events5min = metrics?.summary.events_last_5min ?? 0
  const eventsPerMin = metrics ? Math.round((metrics.summary.events_last_5min || 0) / 5) : 0

  // Chart data
  const chartData = metrics?.buckets.map((b) => ({
    time: format(new Date(b.ts), 'HH:mm'),
    events: b.events_total,
    commands: b.commands_total,
  })) ?? []

  return (
    <div className="flex flex-col gap-10">
      <FadeIn>
        <h1 className="text-h1 mb-2">Overview</h1>
        <p className="text-body-lg text-ink-400">
          {health?.routers_online ?? 0} of {health?.routers ?? 0} routers online · {eventsPerMin} events/min
        </p>
      </FadeIn>

      {/* Hero stats grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
        <FadeIn delay={0.05}>
          <Card padding="lg">
            <Stat
              label="Routers online"
              value={onlineCount}
              sub={`${totalRouters} total`}
              accent={onlineCount === totalRouters && totalRouters > 0 ? 'success' : onlineCount === 0 ? 'danger' : 'warning'}
              icon={<Radio className="w-3.5 h-3.5" />}
            />
          </Card>
        </FadeIn>
        <FadeIn delay={0.1}>
          <Card padding="lg">
            <Stat
              label="Events · last 5 min"
              value={events5min}
              sub={`${eventsPerMin}/min average`}
              icon={<Activity className="w-3.5 h-3.5" />}
            />
          </Card>
        </FadeIn>
        <FadeIn delay={0.15}>
          <Card padding="lg">
            <Stat
              label="Commands this min"
              value={metrics?.summary.commands_this_min ?? 0}
              sub={`${metrics?.buckets.reduce((s, b) => s + b.commands_total, 0) ?? 0} last hour`}
              icon={<Cpu className="w-3.5 h-3.5" />}
            />
          </Card>
        </FadeIn>
        <FadeIn delay={0.2}>
          <Card padding="lg">
            <Stat
              label="Alerts"
              value={alerts?.alerts.length ?? 0}
              sub="unacknowledged"
              accent={(alerts?.alerts.length ?? 0) > 0 ? 'warning' : 'default'}
              icon={<Server className="w-3.5 h-3.5" />}
            />
          </Card>
        </FadeIn>
      </div>

      {/* Chart + Live feed */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <FadeIn delay={0.25} className="lg:col-span-2">
          <Card padding="lg">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-h3">Activity</h2>
                <p className="text-caption text-ink-500 mt-1">Events and commands over the last hour</p>
              </div>
              <Pill tone="info"><TrendingUp className="w-3 h-3" /> live</Pill>
            </div>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={chartData}>
                  <defs>
                    <linearGradient id="events-grad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#0a84ff" stopOpacity={0.5} />
                      <stop offset="100%" stopColor="#0a84ff" stopOpacity={0} />
                    </linearGradient>
                    <linearGradient id="cmds-grad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#30d158" stopOpacity={0.4} />
                      <stop offset="100%" stopColor="#30d158" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <XAxis dataKey="time" stroke="#6e6e73" fontSize={11} tickLine={false} axisLine={false} />
                  <YAxis stroke="#6e6e73" fontSize={11} tickLine={false} axisLine={false} width={30} />
                  <Tooltip
                    contentStyle={{ background: 'rgba(28,28,30,0.95)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 12, fontSize: 12 }}
                    labelStyle={{ color: '#a1a1a6' }}
                  />
                  <Area type="monotone" dataKey="events" stroke="#0a84ff" fill="url(#events-grad)" strokeWidth={2} />
                  <Area type="monotone" dataKey="commands" stroke="#30d158" fill="url(#cmds-grad)" strokeWidth={2} />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </Card>
        </FadeIn>

        <FadeIn delay={0.3}>
          <Card padding="none" className="h-full flex flex-col">
            <div className="p-6 border-b border-white/5">
              <div className="flex items-center justify-between">
                <h2 className="text-h3">Live feed</h2>
                <Pill tone="success"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />live</Pill>
              </div>
              <p className="text-caption text-ink-500 mt-1">Most recent 50 events</p>
            </div>
            <div className="flex-1 overflow-y-auto max-h-[400px] divide-y divide-white/5">
              {live.length === 0 && (
                <div className="p-8 text-center text-ink-500 text-caption">
                  Waiting for events…
                </div>
              )}
              {live.map((ev, i) => (
                <div key={ev.id + '-' + i} className="p-4 hover:bg-white/[0.02] transition-colors">
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-small font-medium text-ink-200">{ev.event_type}</span>
                    <span className="text-[10px] text-ink-500">
                      {formatDistanceToNow(new Date(ev.received_at), { addSuffix: true })}
                    </span>
                  </div>
                  <div className="text-caption text-ink-500 truncate">{ev.router_id}</div>
                </div>
              ))}
            </div>
          </Card>
        </FadeIn>
      </div>
    </div>
  )
}
