'use client';

import { useEffect, useRef, useState } from 'react';
import { AdminShell } from '@/components/AdminShell';
import { getEvents, StoredEvent } from '@/lib/api';

const SUBJECTS = ['', 'signals.tip', 'signals.task', 'signals.tip.served', 'signals.tip.feedback', 'signals.task.synced'];

export default function EventsPage() {
  const [events, setEvents] = useState<StoredEvent[]>([]);
  const [subject, setSubject] = useState('');
  const [userId, setUserId] = useState('');
  const [live, setLive] = useState(true);
  const [error, setError] = useState('');
  const sinceRef = useRef(0);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const fetchEvents = async (reset = false) => {
    try {
      const since = reset ? 0 : sinceRef.current;
      const res = await getEvents({ subject: subject || undefined, userId: userId || undefined, limit: 100, since });
      sinceRef.current = res.nextSince;
      setEvents((prev) => {
        const next = reset ? res.events : [...prev, ...res.events];
        return next.slice(-500); // keep last 500
      });
      setError('');
    } catch (e: any) {
      setError(e.message);
    }
  };

  useEffect(() => {
    sinceRef.current = 0;
    fetchEvents(true);
  }, [subject, userId]);

  useEffect(() => {
    if (live) {
      timerRef.current = setInterval(() => fetchEvents(false), 2000);
    } else if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    return () => { if (timerRef.current) clearInterval(timerRef.current); };
  }, [live, subject, userId]);

  return (
    <AdminShell>
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h1 className="text-xl font-semibold">Event stream</h1>
          <div className="flex items-center gap-2">
            <label className="flex items-center gap-1.5 text-sm text-gray-400 cursor-pointer">
              <input type="checkbox" checked={live} onChange={(e) => setLive(e.target.checked)} className="accent-indigo-500" />
              Live
            </label>
            <button onClick={() => { sinceRef.current = 0; fetchEvents(true); }} className="text-xs text-gray-400 hover:text-white border border-gray-700 rounded px-2 py-1">
              Refresh
            </button>
          </div>
        </div>

        <div className="flex gap-3">
          <select value={subject} onChange={(e) => setSubject(e.target.value)} className="bg-gray-900 border border-gray-700 rounded px-2 py-1 text-sm text-gray-300">
            {SUBJECTS.map((s) => <option key={s} value={s}>{s || 'All subjects'}</option>)}
          </select>
          <input
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
            placeholder="Filter by user ID"
            className="bg-gray-900 border border-gray-700 rounded px-2 py-1 text-sm text-gray-300 w-64"
          />
        </div>

        {error && <p className="text-red-400 text-sm">{error}</p>}

        <div className="font-mono text-xs space-y-1 max-h-[70vh] overflow-y-auto">
          {events.length === 0 && (
            <p className="text-gray-500 text-sm">No events yet. Waiting…</p>
          )}
          {[...events].reverse().map((e) => (
            <div key={e.id} className="flex gap-3 border-b border-gray-800 pb-1">
              <span className="text-gray-600 w-12 flex-shrink-0">{e.id}</span>
              <span className="text-gray-500 w-24 flex-shrink-0">{e.ts.slice(11, 19)}</span>
              <span className="text-indigo-400 w-40 flex-shrink-0">{e.subject}</span>
              <span className="text-gray-300 break-all">{JSON.stringify(e.payload)}</span>
            </div>
          ))}
        </div>
      </div>
    </AdminShell>
  );
}
