'use client';

import Link from 'next/link';
import { ArrowLeft, Clock3, Flame, History, TrendingDown, TrendingUp } 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 { getHermesHistory, hermesTasks } from '@/lib/hermes';
import {
  collectBackupEntries,
  collectCronEntries,
  collectSessionEvents,
  collectSessionEntries,
  collectWatchdogAlerts,
  emptyTelemetryState,
  loadAllHermesTelemetry,
  type HermesTelemetryState,
} from '@/lib/hermes-telemetry-client';

export default function HermesHistoryPage() {
  const { selectedInstance } = useHermesInstance();
  const [telemetry, setTelemetry] = useState<HermesTelemetryState>(emptyTelemetryState);
  const [telemetryError, setTelemetryError] = useState<string | null>(null);
  const history = useMemo(() => getHermesHistory(selectedInstance), [selectedInstance]);
  const filteredTasks = useMemo(
    () => (selectedInstance === 'all' ? hermesTasks : hermesTasks.filter((task) => task.instanceId === selectedInstance)),
    [selectedInstance],
  );
  const completedTrend = history.map((point) => point.completed);
  const failedTrend = history.map((point) => point.failed);
  const maxValue = Math.max(...history.flatMap((point) => [point.completed, point.failed, point.blocked, point.active]), 1);
  const weeklyCompleted = completedTrend.reduce((sum, value) => sum + value, 0);
  const weeklyFailed = failedTrend.reduce((sum, value) => sum + value, 0);
  const blocked = history.reduce((sum, point) => sum + point.blocked, 0);
  const tasksWithDuration = filteredTasks.filter((task) => task.durationMs);
  const avgDuration = Math.round(
    tasksWithDuration.reduce((sum, task) => sum + (task.durationMs ?? 0), 0) /
    Math.max(1, tasksWithDuration.length) / 60000,
  );
  const liveAlerts = useMemo(() => collectWatchdogAlerts(telemetry, selectedInstance).slice(0, 10), [telemetry, selectedInstance]);
  const liveBackups = useMemo(() => collectBackupEntries(telemetry, selectedInstance).slice(0, 10), [telemetry, selectedInstance]);
  const liveCron = useMemo(() => collectCronEntries(telemetry, selectedInstance).slice(0, 10), [telemetry, selectedInstance]);
  const liveSessions = useMemo(() => collectSessionEntries(telemetry, selectedInstance).slice(0, 10), [telemetry, selectedInstance]);
  const liveEvents = useMemo(() => collectSessionEvents(telemetry, selectedInstance).slice(0, 10), [telemetry, selectedInstance]);

  useEffect(() => {
    let active = true;
    const load = async () => {
      try {
        const next = await loadAllHermesTelemetry();
        if (!active) return;
        setTelemetry(next);
        setTelemetryError(null);
      } catch (err) {
        if (!active) return;
        setTelemetryError(err instanceof Error ? err.message : String(err));
      }
    };
    void load();
    return () => {
      active = false;
    };
  }, []);

  const failureReasons = [
    ['CI failures', 9],
    ['Missing credentials', 6],
    ['Deployment instability', 4],
    ['Unclear requirements', 3],
    ['External dependency', 2],
  ] as const;

  return (
    <HermesShell
      title="Historical Activity"
      description="Trendlines and summary analytics for completed, failed, blocked, and active work over time."
      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-2 xl:grid-cols-4">
        <MetricCard label="Completed over window" value={weeklyCompleted} tone="success" icon={<TrendingUp className="h-5 w-5" />} />
        <MetricCard label="Failed over window" value={weeklyFailed} tone="danger" icon={<TrendingDown className="h-5 w-5" />} />
        <MetricCard label="Blocked over window" value={blocked} tone="warning" icon={<Flame className="h-5 w-5" />} />
        <MetricCard label="Avg task duration" value={`${avgDuration}m`} tone="info" icon={<Clock3 className="h-5 w-5" />} />
      </section>

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <MetricCard label="Live events" value={liveEvents.length} tone="info" icon={<History className="h-5 w-5" />} helpText="From Hermes session JSONL" />
        <MetricCard label="Live cron jobs" value={liveCron.length} tone="info" icon={<Clock3 className="h-5 w-5" />} helpText="From hermes cron list" />
        <MetricCard label="Watchdog alerts" value={liveAlerts.length} tone={liveAlerts.some((a) => a.severity === 'critical') ? 'danger' : liveAlerts.some((a) => a.severity === 'warn') ? 'warning' : 'default'} icon={<Flame className="h-5 w-5" />} helpText="From watchdog logs" />
        <MetricCard label="Backup commits" value={liveBackups.length} tone="success" icon={<TrendingUp className="h-5 w-5" />} helpText="From backup git history" />
      </section>

      <SectionCard
        title="Live artifact timeline"
        subtitle="Real session events, sessions, cron, watchdog, and backup history from the Hermes telemetry endpoint. Message content is redacted at the backend."
        actions={<Badge variant={telemetryError ? 'error' : 'success'}>{telemetryError ? 'Telemetry unavailable' : 'Live telemetry'}</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 xl:grid-cols-5">
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Recent events</p>
              <div className="mt-3 space-y-2 text-sm text-[var(--bl-text-secondary)]">
                {liveEvents.length > 0 ? liveEvents.map((event) => (
                  <div key={`${event.instanceId}-${event.id}`} className="flex items-start justify-between gap-3">
                    <span className="line-clamp-2">{event.summary}</span>
                    <HermesInstanceBadge instanceId={event.instanceId} />
                  </div>
                )) : <p>No session events returned.</p>}
              </div>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Recent sessions</p>
              <div className="mt-3 space-y-2 text-sm text-[var(--bl-text-secondary)]">
                {liveSessions.length > 0 ? liveSessions.map((session) => (
                  <div key={`${session.instanceId}-${session.id}`} className="flex items-center justify-between gap-3">
                    <span className="truncate">{session.displayName ?? session.sessionKey}</span>
                    <HermesInstanceBadge instanceId={session.instanceId} />
                  </div>
                )) : <p>No session entries returned.</p>}
              </div>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Recent watchdog alerts</p>
              <div className="mt-3 space-y-2 text-sm text-[var(--bl-text-secondary)]">
                {liveAlerts.length > 0 ? liveAlerts.map((alert) => (
                  <div key={`${alert.instanceId}-${alert.timestamp}-${alert.message}`} className="flex items-start justify-between gap-3">
                    <span className="line-clamp-2">{alert.message}</span>
                    <div className="flex shrink-0 items-center gap-2">
                      <Badge variant={alert.severity === 'critical' ? 'error' : alert.severity === 'warn' ? 'warning' : 'info'}>{alert.severity}</Badge>
                      <HermesInstanceBadge instanceId={alert.instanceId} />
                    </div>
                  </div>
                )) : <p>No watchdog alerts returned.</p>}
              </div>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Cron entries</p>
              <div className="mt-3 space-y-2 text-sm text-[var(--bl-text-secondary)]">
                {liveCron.length > 0 ? liveCron.map((entry) => (
                  <div key={`${entry.instanceId}-${entry.id}`} className="flex items-center justify-between gap-3">
                    <span className="truncate">{entry.name}</span>
                    <HermesInstanceBadge instanceId={entry.instanceId} />
                  </div>
                )) : <p>No cron entries returned.</p>}
              </div>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Backup history</p>
              <div className="mt-3 space-y-2 text-sm text-[var(--bl-text-secondary)]">
                {liveBackups.length > 0 ? liveBackups.map((entry) => (
                  <div key={`${entry.instanceId}-${entry.sha}`} className="flex items-center justify-between gap-3">
                    <span className="truncate">{entry.subject}</span>
                    <HermesInstanceBadge instanceId={entry.instanceId} />
                  </div>
                )) : <p>No backup commits returned.</p>}
              </div>
            </div>
          </div>
        )}
      </SectionCard>

      <SectionCard title="Weekly activity chart" subtitle="Accessible bar chart built with standard layout primitives.">
        <div className="overflow-x-auto">
          <div className="flex min-w-[48rem] items-end gap-4 rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-5">
            {history.map((point) => (
              <div key={point.label} className="flex flex-1 flex-col items-center gap-2">
                <div className="flex h-64 w-full items-end gap-1">
                  <div className="w-1/3 rounded-t-md bg-[var(--bl-success)]" style={{ height: `${(point.completed / maxValue) * 100}%` }} />
                  <div className="w-1/3 rounded-t-md bg-[var(--bl-danger)]" style={{ height: `${(point.failed / maxValue) * 100}%` }} />
                  <div className="w-1/3 rounded-t-md bg-[var(--bl-warning)]" style={{ height: `${(point.blocked / maxValue) * 100}%` }} />
                </div>
                <p className="text-xs font-medium text-[var(--bl-text-secondary)]">{point.label}</p>
                <Badge variant="neutral">{point.active} active</Badge>
              </div>
            ))}
          </div>
          <div className="mt-4 flex flex-wrap gap-4 text-sm text-[var(--bl-text-secondary)]">
            <span className="inline-flex items-center gap-2"><span className="h-3 w-3 rounded-full bg-[var(--bl-success)]" />Completed</span>
            <span className="inline-flex items-center gap-2"><span className="h-3 w-3 rounded-full bg-[var(--bl-danger)]" />Failed</span>
            <span className="inline-flex items-center gap-2"><span className="h-3 w-3 rounded-full bg-[var(--bl-warning)]" />Blocked</span>
          </div>
        </div>
      </SectionCard>

      <div className="grid gap-6 lg:grid-cols-2">
        <SectionCard title="Failure categories" subtitle="What keeps showing up in the retry and incident queues.">
          <div className="space-y-3">
            {failureReasons.map(([label, value]) => (
              <div key={label} className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
                <div className="flex items-center justify-between text-sm">
                  <span className="font-medium text-[var(--bl-text-primary)]">{label}</span>
                  <span className="text-[var(--bl-text-secondary)]">{value}</span>
                </div>
                <div className="mt-2 h-2 rounded-full bg-[var(--bl-surface-card)]">
                  <div className="h-2 rounded-full bg-[var(--bl-accent)]" style={{ width: `${(value / 12) * 100}%` }} />
                </div>
              </div>
            ))}
          </div>
        </SectionCard>

        <SectionCard title="Weekly summary" subtitle="Founder-friendly rollup of the operational trendline.">
          <div className="space-y-3 text-sm text-[var(--bl-text-secondary)]">
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">Most active products are cycling through deploy and audit work.</div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">Neglected products are flagged when activity falls past the 14-day threshold.</div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">Average task duration is trending stable, but failure bursts still concentrate in CI-heavy work.</div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">Recommended next action: attack the repeated failure cluster and clear the highest-priority blocked item.</div>
          </div>
        </SectionCard>
      </div>
    </HermesShell>
  );
}
