"use client";
import { ArrowPathIcon } from "@heroicons/react/24/outline";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import toast from "react-hot-toast";
import { get, post } from "../../lib/api";

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

  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 restartMutation = useMutation({
    mutationFn: () => post("/restart", {}),
    onSuccess: () => {
      toast.success("API service restarting...");
      setShowRestartConfirm(false);
      // Retry health check after a delay to see if service is back
      setTimeout(() => {
        queryClient.invalidateQueries({ queryKey: ["api", "health"] });
      }, 3000);
    },
    onError: (error: any) => {
      toast.error("Failed to restart API service");
    },
  });

  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>
          )}
          <button
            onClick={() => setShowRestartConfirm(true)}
            disabled={restartMutation.isPending}
            className="ml-2 p-1.5 rounded hover:bg-gray-200 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            title="Restart API service"
          >
            <ArrowPathIcon
              className={`w-4 h-4 ${
                restartMutation.isPending ? "animate-spin" : ""
              }`}
            />
          </button>
        </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>

      {/* Restart Confirmation Dialog */}
      {showRestartConfirm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-900 rounded-lg shadow-lg p-6 max-w-sm mx-4">
            <h2 className="text-lg font-semibold mb-2">Restart API Service?</h2>
            <p className="text-gray-600 dark:text-gray-400 text-sm mb-6">
              This will gracefully restart the API service. The service will be
              temporarily unavailable.
            </p>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setShowRestartConfirm(false)}
                disabled={restartMutation.isPending}
                className="px-4 py-2 rounded border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => restartMutation.mutate()}
                disabled={restartMutation.isPending}
                className="px-4 py-2 rounded bg-red-600 hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-800 text-white disabled:opacity-50 transition-colors flex items-center gap-2"
              >
                {restartMutation.isPending && (
                  <ArrowPathIcon className="w-4 h-4 animate-spin" />
                )}
                Restart
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
