"use client";

import type { StatusHostInfo } from "@/lib/types";

function formatBytes(bytes: number): string {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
}

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

function ProgressBar({ value, max, color }: { value: number; max: number; color: string }) {
  const pct = max > 0 ? (value / max) * 100 : 0;
  return (
    <div className="w-full h-2 bg-zinc-800 rounded-full overflow-hidden">
      <div className={`h-full rounded-full ${color}`} style={{ width: `${Math.min(pct, 100)}%` }} />
    </div>
  );
}

export default function HostDetail({ host }: { host: StatusHostInfo }) {
  const memPct = host.memory_total_bytes > 0 ? (host.memory_used_bytes / host.memory_total_bytes * 100).toFixed(1) : "0";
  const diskPct = host.disk_total_bytes > 0 ? (host.disk_used_bytes / host.disk_total_bytes * 100).toFixed(1) : "0";

  return (
    <div className="flex flex-col gap-3">
      <div className="text-xs text-zinc-500">{host.ip} — {host.os_version}</div>
      <div className="text-xs text-zinc-500">Uptime: {formatUptime(host.uptime_seconds)}</div>

      <div>
        <div className="flex justify-between text-xs mb-1"><span>CPU</span><span>{host.cpu_percent.toFixed(1)}%</span></div>
        <ProgressBar value={host.cpu_percent} max={100} color={host.cpu_percent > 80 ? "bg-amber-500" : "bg-emerald-500"} />
      </div>

      <div>
        <div className="flex justify-between text-xs mb-1"><span>Memory</span><span>{memPct}% ({formatBytes(host.memory_used_bytes)} / {formatBytes(host.memory_total_bytes)})</span></div>
        <ProgressBar value={host.memory_used_bytes} max={host.memory_total_bytes} color={parseFloat(memPct) > 85 ? "bg-amber-500" : "bg-emerald-500"} />
      </div>

      <div>
        <div className="flex justify-between text-xs mb-1"><span>Disk</span><span>{diskPct}% ({formatBytes(host.disk_used_bytes)} / {formatBytes(host.disk_total_bytes)})</span></div>
        <ProgressBar value={host.disk_used_bytes} max={host.disk_total_bytes} color={parseFloat(diskPct) > 80 ? "bg-amber-500" : "bg-emerald-500"} />
      </div>

      {host.pending_updates >= 0 && (
        <div className="text-xs">
          Updates: {host.pending_updates}
          {host.pending_security_updates > 0 && (
            <span className="ml-2 px-1.5 py-0.5 bg-amber-500/20 text-amber-400 rounded text-[10px]">
              {host.pending_security_updates} security
            </span>
          )}
        </div>
      )}
    </div>
  );
}
