"use client";
import { useState, useEffect } from "react";

export default function HealthStatus() {
  const [health, setHealth] = useState<{ status?: string }>({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const checkHealth = async () => {
      try {
        setLoading(true);
        const response = await fetch(`${process.env.BACKEND_URL}/health`);

        if (!response.ok) {
          throw new Error(`Server responded with status: ${response.status}`);
        }

        const data = await response.json();
        setHealth(data);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to check health status"
        );
      } finally {
        setLoading(false);
      }
    };

    checkHealth();
  }, []);

  return (
    <div className="health-status">
      <h2>Backend Health Status</h2>
      {loading ? (
        <p>Checking backend status...</p>
      ) : error ? (
        <div className="error">
          <p>Error: {error}</p>
        </div>
      ) : (
        <div className="status">
          <p>
            Status:{" "}
            <span
              className={health.status === "ok" ? "status-ok" : "status-error"}
            >
              {health.status || "unknown"}
            </span>
          </p>
        </div>
      )}
    </div>
  );
}
