"use client";

import type { SystemHealthResponse } from "@/api/generated/model";
import { DashboardSection } from "./DashboardSection";
import { DashboardEmptyState } from "./DashboardEmptyState";

interface GatewayHealthPanelProps {
  health: SystemHealthResponse | null;
  isLoading?: boolean;
  hasGateways: boolean;
}

function pctBar(pct: number | null | undefined) {
  if (pct == null) return null;
  const clamped = Math.min(100, Math.max(0, pct));
  const color =
    clamped > 90
      ? "bg-[color:var(--danger)]"
      : clamped > 75
        ? "bg-[color:var(--warning)]"
        : "bg-[color:var(--success)]";
  return (
    <div className="flex items-center gap-2">
      <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[color:var(--surface-strong)]">
        <div
          className={`h-full rounded-full transition-all ${color}`}
          style={{ width: `${clamped}%` }}
        />
      </div>
      <span className="w-10 text-right text-xs tabular-nums text-muted">
        {clamped.toFixed(0)}%
      </span>
    </div>
  );
}

function fmtUptime(seconds: number | null | undefined): string {
  if (seconds == null) return "—";
  const d = Math.floor(seconds / 86400);
  const h = Math.floor((seconds % 86400) / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}

function fmtBytes(bytes: number | null | undefined): string {
  if (bytes == null) return "";
  if (bytes >= 1e9) return ` (${(bytes / 1e9).toFixed(1)} GB)`;
  if (bytes >= 1e6) return ` (${(bytes / 1e6).toFixed(0)} MB)`;
  return "";
}

export function GatewayHealthPanel({
  health,
  isLoading = false,
  hasGateways,
}: GatewayHealthPanelProps) {
  if (!hasGateways) return null;

  const c = health?.current;

  return (
    <DashboardSection title="Gateway Health">
      {isLoading && !health ? (
        <DashboardEmptyState message="Loading health data…" />
      ) : !health || (!c?.cpu_pct && !c?.memory_pct && !c?.uptime_seconds) ? (
        <DashboardEmptyState message="Health data unavailable. The gateway may not expose system metrics." />
      ) : (
        <div className="space-y-3">
          {/* CPU */}
          {c.cpu_pct != null && (
            <div>
              <p className="mb-1 text-xs font-medium text-muted">CPU</p>
              {pctBar(c.cpu_pct)}
              {c.load_avg_1m != null && (
                <p className="mt-0.5 text-[11px] text-muted">
                  load avg {c.load_avg_1m.toFixed(2)}
                  {c.load_avg_5m != null ? ` / ${c.load_avg_5m.toFixed(2)}` : ""}
                  {c.load_avg_15m != null ? ` / ${c.load_avg_15m.toFixed(2)}` : ""}
                </p>
              )}
            </div>
          )}

          {/* RAM */}
          {c.memory_pct != null && (
            <div>
              <p className="mb-1 text-xs font-medium text-muted">
                Memory{fmtBytes(c.memory_used_bytes)}
              </p>
              {pctBar(c.memory_pct)}
            </div>
          )}

          {/* Disk */}
          {c.disk_pct != null && (
            <div>
              <p className="mb-1 text-xs font-medium text-muted">
                Disk{fmtBytes(c.disk_used_bytes)}
              </p>
              {pctBar(c.disk_pct)}
            </div>
          )}

          {/* Uptime / hostname */}
          <div className="flex flex-wrap gap-4 border-t border-[color:var(--border)] pt-3 text-xs text-muted">
            {c.uptime_seconds != null && (
              <span>
                Uptime <span className="font-medium text-strong">{fmtUptime(c.uptime_seconds)}</span>
              </span>
            )}
            {c.hostname && (
              <span className="truncate">
                Host <span className="font-medium text-strong">{c.hostname}</span>
              </span>
            )}
            {c.platform && (
              <span>{c.platform}</span>
            )}
          </div>
        </div>
      )}
    </DashboardSection>
  );
}
