'use client';

import Link from 'next/link';
import { ArrowLeft, Brain, Gauge, ShieldAlert, ServerCog, Wand2 } from 'lucide-react';
import { Badge, Button } from '@/components/ui/Primitives';
import { useEffect, useMemo, useState } from 'react';
import { HermesShell, MetricCard, SectionCard } from '@/components/hermes-shell';
import { HermesInstanceBadge } from '@/components/hermes-instance-switcher';
import { useHermesInstance } from '@/lib/hermes-instance-context';
import { getHermesAgents, HERMES_INSTANCES } from '@/lib/hermes';
import {
  emptyTelemetryState,
  loadAllHermesTelemetry,
  type HermesTelemetryState,
} from '@/lib/hermes-telemetry-client';

export default function HermesAgentsPage() {
  const { selectedInstance } = useHermesInstance();
  const agents = useMemo(() => getHermesAgents(selectedInstance), [selectedInstance]);
  const healthy = agents.filter((agent) => agent.status === 'healthy').length;
  const degraded = agents.filter((agent) => agent.status === 'degraded').length;
  const offline = agents.filter((agent) => agent.status === 'offline').length;

  // Real per-instance memory + skills inventory from the Phase 3 telemetry
  // endpoint. The agent statuses above remain seed-data (status observability
  // needs a separate ingestion contract); the inventory below is genuine
  // when the `hermes` CLI is reachable, status:'unknown' otherwise.
  const [telemetry, setTelemetry] = useState<HermesTelemetryState>(emptyTelemetryState);
  const [telemetryError, setTelemetryError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    const load = async () => {
      try {
        const next = await loadAllHermesTelemetry();
        if (controller.signal.aborted) return;
        setTelemetry(next);
        setTelemetryError(null);
      } catch (err) {
        if (controller.signal.aborted) return;
        setTelemetryError(err instanceof Error ? err.message : String(err));
      }
    };
    void load();
    return () => controller.abort();
  }, []);

  return (
    <HermesShell
      title="Agent & Tool Observability"
      description="Status board for Hermes core, integrations, runners, scheduler, and notification tooling."
      actions={<Button asChild><Link href="/hermes"><ArrowLeft className="mr-2 h-4 w-4" />Back to mission control</Link></Button>}
    >
      <section className="grid gap-4 md:grid-cols-3">
        <MetricCard label="Healthy" value={healthy} tone="success" icon={<Gauge className="h-5 w-5" />} />
        <MetricCard label="Degraded" value={degraded} tone="warning" icon={<ShieldAlert className="h-5 w-5" />} />
        <MetricCard label="Offline" value={offline} tone="danger" icon={<ServerCog className="h-5 w-5" />} />
      </section>

      <SectionCard title="Tool and integration health" subtitle="Each item includes last success, failure rate, latency, and config warnings.">
        <div className="grid gap-4 lg:grid-cols-2">
          {agents.map((agent) => (
            <div key={agent.id} className="rounded-3xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-5">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <p className="text-lg font-semibold text-[var(--bl-text-primary)]">{agent.name}</p>
                  <p className="text-sm text-[var(--bl-text-secondary)]">{agent.type} · {agent.callsToday} calls today</p>
                </div>
                <div className="flex flex-col items-end gap-2">
                  <Badge variant={agent.status === 'healthy' ? 'success' : agent.status === 'degraded' ? 'warning' : 'error'}>{agent.status}</Badge>
                  <HermesInstanceBadge instanceId={agent.instanceId} />
                </div>
              </div>
              <div className="mt-4 grid gap-3 text-sm text-[var(--bl-text-secondary)] md:grid-cols-2">
                <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">Last success: {agent.lastSuccessAt ? new Date(agent.lastSuccessAt).toLocaleString() : '—'}</div>
                <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">Last failure: {agent.lastFailureAt ? new Date(agent.lastFailureAt).toLocaleString() : '—'}</div>
                <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">Failure rate: {(agent.failureRate * 100).toFixed(1)}%</div>
                <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">Latency: {agent.averageLatencyMs ?? '—'}ms</div>
              </div>
              {agent.configIssue ? <div className="mt-3 rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-warning-muted)] p-3 text-sm text-[var(--bl-warning)]">{agent.configIssue}</div> : null}
            </div>
          ))}
        </div>
      </SectionCard>

      {/* --- Real memory + skills inventory from /api/hermes/telemetry --- */}
      <SectionCard
        title="Memory & Skills inventory (live)"
        subtitle="Read directly from `hermes memory list` / `hermes skills list` per instance. Sections marked unknown couldn't probe the source on the current host (CLI missing or non-zero exit)."
        actions={<Badge variant={telemetryError ? 'error' : 'success'}>{telemetryError ? 'Probe failed' : 'Live data'}</Badge>}
      >
        {telemetryError ? (
          <p className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4 text-sm text-[var(--bl-warning)]">
            Could not load telemetry: {telemetryError}
          </p>
        ) : (
          <div className="grid gap-4 lg:grid-cols-2">
            {HERMES_INSTANCES.filter((inst) => selectedInstance === 'all' || selectedInstance === inst.id).map((inst) => {
              const snapshot = telemetry[inst.id];
              const memory = snapshot?.memory;
              const skills = snapshot?.skills;
              return (
                <div key={inst.id} className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <p className="text-base font-semibold text-[var(--bl-text-primary)]">{inst.label}</p>
                      <p className="text-xs text-[var(--bl-text-secondary)]">{inst.description}</p>
                    </div>
                    <HermesInstanceBadge instanceId={inst.id} />
                  </div>

                  <div className="mt-4 space-y-3">
                    <div className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">
                      <div className="flex items-center justify-between gap-2 text-sm">
                        <span className="inline-flex items-center gap-2 font-medium text-[var(--bl-text-primary)]"><Brain className="h-4 w-4" />Memory items</span>
                        <Badge variant={memory?.status === 'up' ? 'success' : memory?.status === 'unknown' ? 'warning' : 'neutral'}>
                          {snapshot ? `${memory?.items.length ?? 0} · ${memory?.status ?? 'loading'}` : 'loading'}
                        </Badge>
                      </div>
                      {memory && memory.items.length > 0 ? (
                        <ul className="mt-2 space-y-1 text-xs text-[var(--bl-text-secondary)]">
                          {memory.items.slice(0, 5).map((m) => (
                            <li key={m.id} className="truncate"><span className="text-[var(--bl-text-tertiary)]">{m.type}:</span> {m.key} — {m.summary}</li>
                          ))}
                          {memory.items.length > 5 ? <li className="text-[var(--bl-text-tertiary)]">+ {memory.items.length - 5} more</li> : null}
                        </ul>
                      ) : null}
                    </div>

                    <div className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">
                      <div className="flex items-center justify-between gap-2 text-sm">
                        <span className="inline-flex items-center gap-2 font-medium text-[var(--bl-text-primary)]"><Wand2 className="h-4 w-4" />Skills</span>
                        <Badge variant={skills?.status === 'up' ? 'success' : skills?.status === 'unknown' ? 'warning' : 'neutral'}>
                          {snapshot ? `${skills?.items.length ?? 0} · ${skills?.status ?? 'loading'}` : 'loading'}
                        </Badge>
                      </div>
                      {skills && skills.items.length > 0 ? (
                        <ul className="mt-2 grid gap-1 text-xs text-[var(--bl-text-secondary)] md:grid-cols-2">
                          {skills.items.slice(0, 8).map((s) => (
                            <li key={s.id} className="truncate"><Badge variant={s.enabled ? 'success' : 'neutral'}>{s.enabled ? 'on' : 'off'}</Badge> {s.name}</li>
                          ))}
                          {skills.items.length > 8 ? <li className="text-[var(--bl-text-tertiary)]">+ {skills.items.length - 8} more</li> : null}
                        </ul>
                      ) : null}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </SectionCard>

      <SectionCard title="Ecosystem coverage" subtitle="The dashboard should make each subsystem accountable and observable.">
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {['Hermes core', 'GitHub integration', 'Local VM runner', 'CLI runner', 'Scheduler / cron', 'Deployment tools', 'Monitoring tools', 'Notification tools', 'Model / LLM provider', 'Secrets / config health', 'OpenClaw integration placeholder', 'Telemetry ingest'].map((item) => (
            <div key={item} className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4 text-sm text-[var(--bl-text-secondary)]">{item}</div>
          ))}
        </div>
      </SectionCard>
    </HermesShell>
  );
}
