// Routers page: list with online/offline status, last seen, queued commands.

import { useQuery } from '@tanstack/react-query'
import { formatDistanceToNow } from 'date-fns'
import { Cpu, Radio } from 'lucide-react'
import { api } from '../lib/api'
import { Card, FadeIn, Pill, Skeleton } from '../components/ui'

export function RoutersPage() {
  const { data, isLoading } = useQuery({
    queryKey: ['routers'],
    queryFn: api.routers,
    refetchInterval: 5_000,
  })

  const routers = data?.routers ?? []
  const online = routers.filter((r) => r.online).length

  return (
    <div className="flex flex-col gap-8">
      <FadeIn>
        <div className="flex items-end justify-between">
          <div>
            <h1 className="text-h1 mb-2">Routers</h1>
            <p className="text-body-lg text-ink-400">{online} online · {routers.length} total</p>
          </div>
        </div>
      </FadeIn>

      {isLoading && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-32" />)}
        </div>
      )}

      {!isLoading && routers.length === 0 && (
        <Card padding="lg" className="text-center">
          <Radio className="w-10 h-10 mx-auto mb-3 text-ink-500" />
          <p className="text-body text-ink-300">No routers connected yet</p>
          <p className="text-caption text-ink-500 mt-1">Routers will appear here once they connect via WebSocket</p>
        </Card>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {routers.map((r, i) => (
          <FadeIn key={r.id} delay={i * 0.03}>
            <Card hover padding="md">
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-2">
                  <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${r.online ? 'bg-emerald-500/15' : 'bg-white/5'}`}>
                    <Radio className={`w-4 h-4 ${r.online ? 'text-emerald-400' : 'text-ink-500'}`} />
                  </div>
                  <div>
                    <div className="text-body font-medium text-ink-100">{r.id}</div>
                    <div className="text-caption text-ink-500">
                      {formatDistanceToNow(new Date(r.last_seen), { addSuffix: true })}
                    </div>
                  </div>
                </div>
                <Pill tone={r.online ? 'success' : 'danger'}>{r.online ? 'online' : 'offline'}</Pill>
              </div>
              {r.queued_commands > 0 && (
                <div className="flex items-center gap-2 mt-3 pt-3 border-t border-white/5 text-caption text-ink-400">
                  <Cpu className="w-3.5 h-3.5" />
                  {r.queued_commands} command{r.queued_commands !== 1 ? 's' : ''} queued
                </div>
              )}
            </Card>
          </FadeIn>
        ))}
      </div>
    </div>
  )
}
