"use client";

import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";

type Status = "connected" | "disconnected" | "checking";

export function ApiStatus() {
  const [status, setStatus] = useState<Status>("checking");

  useEffect(() => {
    const checkHealth = async () => {
      try {
        const apiUrl =
          process.env.NEXT_PUBLIC_STEMEDB_API_URL || "http://127.0.0.1:18180";
        const response = await fetch(`${apiUrl}/health`, {
          cache: "no-store",
        });
        setStatus(response.ok ? "connected" : "disconnected");
      } catch {
        setStatus("disconnected");
      }
    };

    checkHealth();
    const interval = setInterval(checkHealth, 30000); // Check every 30s
    return () => clearInterval(interval);
  }, []);

  const statusConfig = {
    connected: {
      color: "bg-status-healthy",
      label: "Connected",
    },
    disconnected: {
      color: "bg-status-error",
      label: "Disconnected",
    },
    checking: {
      color: "bg-status-warning",
      label: "Checking...",
    },
  };

  const config = statusConfig[status];

  return (
    <div className="flex items-center gap-2 text-sm">
      <span
        className={cn("h-2 w-2 rounded-full", config.color)}
        aria-hidden="true"
      />
      <span className="text-muted-foreground">{config.label}</span>
    </div>
  );
}
