import { useEffect, useRef, useState } from 'react'
import { Activity, Wifi, WifiOff } from 'lucide-react'

interface FeedEvent {
  ts: string
  host: string
  path: string
  matched: boolean
  skill_id: string | null
  score: number | null
  tokens_before: number
  tokens_after: number
  saving_pct: number
  latency_ms: number
  status: number
  request_id?: string
}

const MAX_ROWS = 100

export function useLiveFeed() {
  const [events, setEvents] = useState<FeedEvent[]>([])
  const [connected, setConnected] = useState(false)
  const esRef = useRef<EventSource | null>(null)

  useEffect(() => {
    const es = new EventSource('/bibividi/events')
    esRef.current = es
    es.onopen = () => setConnected(true)
    es.onerror = () => setConnected(false)
    es.onmessage = (e) => {
      const data = JSON.parse(e.data)
      if (data.type === 'connected') { setEvents([]); setConnected(true); return }
      setEvents((prev) => [data as FeedEvent, ...prev].slice(0, MAX_ROWS))
    }
    return () => es.close()
  }, [])

  return { events, connected }
}

export default function LiveFeed() {
  const { events, connected } = useLiveFeed()

  const fmt = (ts: string) => new Date(ts).toLocaleTimeString()

  return (
    <div>
      <div className="page-title">
        <Activity size={20} color="var(--accent-light)" />
        Live Feed
      </div>

      <div className="feed-status">
        <span className={connected ? 'dot dot-green' : 'dot dot-red'} />
        {connected ? 'Connected to proxy' : 'Disconnected — waiting for proxy…'}
        <span className="muted fine ml-auto">{events.length} / {MAX_ROWS} events</span>
      </div>

      {events.length === 0 ? (
        <div className="empty-state">
          {connected
            ? <><Wifi size={28} /><p>Waiting for requests through the proxy…</p></>
            : <><WifiOff size={28} /><p>Start the proxy with <code>bibividi start</code></p></>
          }
        </div>
      ) : (
        <div className="section">
          <div style={{ overflowX: 'auto' }}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>Time</th>
                  <th>Host</th>
                  <th>Match</th>
                  <th>Skill</th>
                  <th>Score</th>
                  <th>Before</th>
                  <th>After</th>
                  <th>Saving</th>
                  <th>Latency</th>
                  <th>HTTP</th>
                </tr>
              </thead>
              <tbody>
                {events.map((ev, i) => (
                  <tr key={i}>
                    <td className="mono nowrap">{fmt(ev.ts)}</td>
                    <td className="nowrap">{ev.host}</td>
                    <td>
                      {ev.matched
                        ? <span className="badge badge-green">✓</span>
                        : <span className="muted">—</span>
                      }
                    </td>
                    <td className="mono nowrap">
                      {ev.skill_id ?? <span className="muted">—</span>}
                    </td>
                    <td>{ev.score != null ? ev.score.toFixed(2) : <span className="muted">—</span>}</td>
                    <td>{ev.tokens_before.toLocaleString()}</td>
                    <td>{ev.tokens_after.toLocaleString()}</td>
                    <td className={ev.saving_pct >= 50 ? 'green' : ev.saving_pct > 0 ? 'yellow' : ''}>
                      {ev.saving_pct > 0 ? `${ev.saving_pct}%` : <span className="muted">—</span>}
                    </td>
                    <td className="nowrap">{ev.latency_ms} ms</td>
                    <td className={ev.status < 400 ? 'green' : 'red'}>{ev.status}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
