"use client";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { get } from "../../lib/api";

export default function ApiHealth() {
  const [responseTime, setResponseTime] = useState<number | null>(null);

  const { data, isLoading, error } = useQuery({
    queryKey: ["api", "health"],
    queryFn: async () => {
      const startTime = performance.now();
      const result = await get("/health");
      const endTime = performance.now();
      setResponseTime(Math.round(endTime - startTime));
      return result;
    },
    refetchInterval: 30000 // Check every 30 seconds
  });

  const isHealthy = data?.status === "healthy";
  const lastChecked = data?.datetime
    ? new Date(data.datetime).toLocaleTimeString()
    : null;

  return (
    <div className="mb-6 p-4 border rounded bg-gray-50 dark:bg-gray-800">
      <div className="flex items-center justify-between mb-4">
        <h3 className="font-semibold">API Health</h3>
        <div className="flex items-center gap-2">
          {isLoading ? (
            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-indigo-600 dark:border-indigo-400"></div>
          ) : (
            <span
              className={`px-2 py-1 rounded text-xs font-medium ${
                isHealthy && !error
                  ? "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
                  : "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
              }`}
            >
              {isHealthy && !error ? "Healthy" : "Unhealthy"}
            </span>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
        <div>
          <span className="font-medium text-gray-700 dark:text-gray-300">
            Status:
          </span>
          <span
            className={`ml-2 ${isHealthy && !error ? "text-green-600" : "text-red-600"}`}
          >
            {isLoading
              ? "Checking..."
              : isHealthy && !error
                ? "Operational"
                : "Issues Detected"}
          </span>
        </div>
        {responseTime !== null && (
          <div>
            <span className="font-medium text-gray-700 dark:text-gray-300">
              Response Time:
            </span>
            <span className="ml-2 text-gray-900 dark:text-gray-100">
              {responseTime}ms
            </span>
          </div>
        )}
        {lastChecked && (
          <div>
            <span className="font-medium text-gray-700 dark:text-gray-300">
              Last Checked:
            </span>
            <span className="ml-2 text-gray-900 dark:text-gray-100">
              {lastChecked}
            </span>
          </div>
        )}
        {error && (
          <div className="md:col-span-2">
            <span className="font-medium text-gray-700 dark:text-gray-300">
              Error:
            </span>
            <span className="ml-2 text-red-600 text-xs">
              {error.message || "Connection failed"}
            </span>
          </div>
        )}
      </div>
    </div>
  );
}
