// Events page: filterable historical event list with live tail.

import { useEffect, useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { format, formatDistanceToNow } from 'date-fns'
import { Search, X } from 'lucide-react'
import { api } from '../lib/api'
import { subscribeSSE } from '../lib/sse'
import { Card, FadeIn, Input, Pill, Skeleton } from '../components/ui'
import type { RouterEvent } from '../lib/types'

const EVENT_TYPES = [
  'dhcp_lease_new', 'dhcp_lease_expire',
  'wan_link_up', 'wan_link_down',
  'wan_dhcp_new', 'wan_dhcp_changed',
  'wifi_connected', 'wifi_disconnected',
  'command_result',
]

export function EventsPage() {
  const [routerFilter, setRouterFilter] = useState('')
  const [typeFilter, setTypeFilter] = useState<string | null>(null)
  const [live, setLive] = useState<RouterEvent[]>([])

  useEffect(() => {
    return subscribeSSE((type, payload) => {
      if (type === 'event') setLive((prev) => [payload as RouterEvent, ...prev].slice(0, 200))
    })
  }, [])

  // Periodically refetch history every 30s
  const { data, isLoading } = useQuery({
    queryKey: ['events', routerFilter, typeFilter],
    queryFn: () => api.events({ limit: 100, router_id: routerFilter, event_type: typeFilter ?? '' }),
    refetchInterval: 30_000,
  })

  // Merge: live events first (deduped by id), then history
  const merged = useMemo(() => {
    const seen = new Set<string>()
    const out: RouterEvent[] = []
    for (const e of live) {
      if (!seen.has(e.id)) { seen.add(e.id); out.push(e) }
    }
    for (const e of data?.events ?? []) {
      if (!seen.has(e.id)) { seen.add(e.id); out.push(e) }
    }
    return out
  }, [live, data])

  const matchesFilter = (e: RouterEvent) =>
    (!routerFilter || e.router_id.toLowerCase().includes(routerFilter.toLowerCase())) &&
    (!typeFilter || e.event_type === typeFilter)

  const filtered = merged.filter(matchesFilter)

  return (
    <div className="flex flex-col gap-8">
      <FadeIn>
        <h1 className="text-h1 mb-2">Events</h1>
        <p className="text-body-lg text-ink-400">{filtered.length} events shown</p>
      </FadeIn>

      <FadeIn delay={0.05}>
        <Card padding="md">
          <div className="flex flex-col md:flex-row gap-3">
            <div className="flex-1">
              <Input
                placeholder="Filter by router id…"
                value={routerFilter}
                onChange={(e) => setRouterFilter(e.target.value)}
              />
            </div>
            <div className="flex flex-wrap gap-1.5">
              {typeFilter && (
                <button
                  onClick={() => setTypeFilter(null)}
                  className="pill bg-blue-500/15 text-blue-300 hover:bg-blue-500/25"
                >
                  {typeFilter} <X className="w-3 h-3" />
                </button>
              )}
              {EVENT_TYPES.map((t) => (
                <button
                  key={t}
                  onClick={() => setTypeFilter(typeFilter === t ? null : t)}
                  className={`pill transition-colors ${
                    typeFilter === t ? 'bg-blue-500/20 text-blue-200' : 'bg-white/5 text-ink-400 hover:bg-white/10'
                  }`}
                >
                  {t}
                </button>
              ))}
            </div>
          </div>
        </Card>
      </FadeIn>

      {isLoading && (
        <div className="flex flex-col gap-2">
          {Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-16" />)}
        </div>
      )}

      {!isLoading && (
        <div className="flex flex-col gap-1.5">
          {filtered.length === 0 && (
            <Card padding="lg" className="text-center">
              <Search className="w-8 h-8 mx-auto mb-2 text-ink-500" />
              <p className="text-body text-ink-300">No events match the current filter</p>
            </Card>
          )}
          {filtered.slice(0, 100).map((ev, i) => (
            <FadeIn key={ev.id + '-' + i} delay={Math.min(i * 0.005, 0.3)}>
              <Card padding="sm" hover>
                <div className="flex items-start gap-4 px-2 py-1">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-small font-medium text-ink-200">{ev.event_type}</span>
                      <Pill tone="neutral" className="text-[10px]">{ev.connection || 'ws'}</Pill>
                    </div>
                    <div className="text-caption text-ink-500 truncate">
                      {ev.router_id}
                      {ev.payload && Object.keys(ev.payload).length > 0 && (
                        <span className="ml-2 text-ink-600">
                          {JSON.stringify(ev.payload).slice(0, 120)}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="text-right shrink-0">
                    <div className="text-caption text-ink-300">
                      {format(new Date(ev.received_at), 'HH:mm:ss')}
                    </div>
                    <div className="text-[10px] text-ink-500">
                      {formatDistanceToNow(new Date(ev.received_at), { addSuffix: true })}
                    </div>
                  </div>
                </div>
              </Card>
            </FadeIn>
          ))}
        </div>
      )}
    </div>
  )
}
