import { useQuery } from "@tanstack/react-query";
import type { InvariantsResponse } from "./types";
import { fetchAdminJson, getAdminErrorMessage } from "./api";

export default function AdminInvariants() {
  const invariantsQuery = useQuery<InvariantsResponse>({
    queryKey: ["admin/health/invariants"],
    queryFn: async () => {
      const data = await fetchAdminJson<InvariantsResponse>("admin/health/invariants");
      if (!data) {
        throw new Error("No invariant response returned.");
      }
      return data;
    },
  });

  if (invariantsQuery.isLoading) {
    return <div className="text-sm text-muted-foreground">Loading invariants...</div>;
  }

  if (invariantsQuery.isError) {
    return (
      <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
        {getAdminErrorMessage(invariantsQuery.error, "Failed to load invariant data.")}
      </div>
    );
  }

  if (!invariantsQuery.data) {
    return <div className="text-sm text-muted-foreground">No invariant data.</div>;
  }

  const data = invariantsQuery.data;

  return (
    <div className="space-y-6">
      <div className="rounded-2xl border border-border/60 bg-card/70 p-6 shadow-sm">
        <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">Invariants</p>
        <h2 className="text-2xl font-semibold">Health checks</h2>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        {Object.entries(data).map(([key, value]) => (
          <div
            key={key}
            className="rounded-xl border border-border/60 bg-card/70 p-4 shadow-sm"
          >
            <p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">{key}</p>
            <p className={`mt-2 text-2xl font-semibold ${value ? "text-red-400" : "text-emerald-400"}`}>
              {String(value)}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}
