"use client";
import { useEffect, useState } from "react";
import { fetchClient } from "@/lib/api-client";

interface Status {
  uptimeSeconds: number;
  memory: Record<string, number>;
  versions: Record<string, string>;
  counts: { vendors: number; orders: number; products: number; chats: number };
}

function formatDuration(seconds: number) {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  return `${h}h ${m}m ${s}s`;
}

export default function SystemStatusCard() {
  const [data, setData] = useState<Status | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        const res = await fetchClient<Status>("/admin/system-status");
        if (mounted) setData(res);
      } catch (e: any) {
        if (mounted) setError(e?.message || "Failed to load status");
      }
    })();
    return () => { mounted = false; };
  }, []);

  return (
    <div className="rounded-lg border border-border/60 bg-background p-4 h-full min-h-[200px]">
      <div className="flex items-start justify-between">
        <div>
          <h2 className="font-medium">System status</h2>
          <p className="text-sm text-muted-foreground mt-1">Uptime, versions, environment</p>
        </div>
        <span className="text-xs px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400">OK</span>
      </div>

      {error && <p className="text-sm text-muted-foreground mt-3">{error}</p>}

      {data && (
        <div className="mt-3 grid grid-cols-2 gap-3 text-sm">
          <div className="space-y-1">
            <div className="text-muted-foreground">Uptime</div>
            <div>{formatDuration(data.uptimeSeconds)}</div>
          </div>
          <div className="space-y-1">
            <div className="text-muted-foreground">Node</div>
            <div>{data.versions?.node}</div>
          </div>
          <div className="space-y-1">
            <div className="text-muted-foreground">Vendors</div>
            <div>{data.counts?.vendors}</div>
          </div>
          <div className="space-y-1">
            <div className="text-muted-foreground">Orders</div>
            <div>{data.counts?.orders}</div>
          </div>
        </div>
      )}
    </div>
  );
}


