'use client';

import { useEffect, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { cn } from '@/lib/cn';

interface SystemHealth {
  probedAtMs: number;
  db: { ok: boolean; latencyMs: number | null };
  redis: { ok: boolean; latencyMs: number | null; queueDepth: number | null };
  docker: { containerCount: number | null };
}

export default function AdminSystemPage() {
  const [health, setHealth] = useState<SystemHealth | null>(null);

  useEffect(() => {
    apiFetch<SystemHealth>('/v1/admin/system').then(setHealth);
    const t = setInterval(() => apiFetch<SystemHealth>('/v1/admin/system').then(setHealth), 5000);
    return () => clearInterval(t);
  }, []);

  return (
    <div className="px-8 py-8">
      <header className="mb-6">
        <h1 className="text-[22px] font-semibold tracking-tight">System health</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          Live probes — Postgres, Redis, BullMQ queue depth, Docker container count. Refreshes
          every 5 seconds.
        </p>
      </header>

      {!health && (
        <p className="mono text-[12px] text-[--color-fg-muted]">Probing…</p>
      )}

      {health && (
        <div className="grid gap-4 md:grid-cols-2">
          <ServiceCard
            title="Postgres"
            ok={health.db.ok}
            primary={
              health.db.latencyMs !== null ? `${health.db.latencyMs}ms` : '—'
            }
            sub="DATABASE_URL · primary store"
          />
          <ServiceCard
            title="Redis"
            ok={health.redis.ok}
            primary={
              health.redis.latencyMs !== null ? `${health.redis.latencyMs}ms` : '—'
            }
            sub="REDIS_URL · BullMQ + pubsub + preview cache"
          />
          <ServiceCard
            title="Build queue"
            ok={health.redis.queueDepth !== null}
            primary={
              health.redis.queueDepth === null
                ? '—'
                : `${health.redis.queueDepth} pending`
            }
            sub="waiting + active + delayed jobs"
          />
          <ServiceCard
            title="Docker containers"
            ok={health.docker.containerCount !== null}
            primary={
              health.docker.containerCount === null
                ? '—'
                : `${health.docker.containerCount} running`
            }
            sub="bmm-mcp-* matching containers"
          />
        </div>
      )}

      {health && (
        <p className="mt-6 mono text-[10.5px] text-[--color-fg-subtle]">
          probed in {health.probedAtMs}ms
        </p>
      )}
    </div>
  );
}

function ServiceCard({
  title,
  ok,
  primary,
  sub,
}: {
  title: string;
  ok: boolean;
  primary: string;
  sub: string;
}) {
  return (
    <div className="panel p-4">
      <div className="flex items-baseline justify-between">
        <div className="text-[11px] uppercase tracking-wider text-[--color-fg-subtle]">{title}</div>
        <span
          className={cn(
            'inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[10.5px] font-medium',
            ok
              ? 'border-emerald-400/40 bg-emerald-400/10 text-emerald-300'
              : 'border-red-400/40 bg-red-400/10 text-red-300',
          )}
        >
          <span
            className={cn(
              'size-1.5 rounded-full',
              ok ? 'bg-emerald-400' : 'bg-red-400',
            )}
            style={ok ? { animation: 'pulse-dot 1.6s ease-in-out infinite' } : undefined}
          />
          {ok ? 'ok' : 'down'}
        </span>
      </div>
      <div className="mt-2 mono text-[22px] font-semibold tabular-nums">{primary}</div>
      <div className="mt-1 text-[12px] text-[--color-fg-muted]">{sub}</div>
    </div>
  );
}
