"use client";

import { useEffect, useMemo, useState } from "react";
import {
  desktopAthenaHealth,
  desktopPing,
  isDesktopRuntime,
  LOCAL_DESKTOP_ATHENA_BASE_URL,
  restartLocalApi,
} from "@/app/lib/desktop";
import { Button } from "./ui/button";

type EngineStatus = "starting" | "healthy" | "offline";

function Dot({ status }: { status: EngineStatus }) {
  const className =
    status === "healthy"
      ? "bg-success"
      : status === "starting"
        ? "bg-warning"
        : "bg-destructive";

  return (
    <span className={`inline-flex h-2.5 w-2.5 rounded-full ${className}`} />
  );
}

export default function AthenaEngineStatus() {
  const [visible, setVisible] = useState(false);
  const [status, setStatus] = useState<EngineStatus>("starting");
  const [statusCode, setStatusCode] = useState<number | null>(null);
  const [isRestarting, setIsRestarting] = useState(false);

  useEffect(() => {
    if (!isDesktopRuntime()) {
      setVisible(false);
      return;
    }

    setVisible(true);

    let mounted = true;

    const refresh = async () => {
      const ping = await desktopPing();

      if (!mounted) {
        return;
      }

      if (ping !== "pong") {
        setStatus("offline");
        setStatusCode(null);
        return;
      }

      const health = await desktopAthenaHealth(LOCAL_DESKTOP_ATHENA_BASE_URL);
      if (!mounted) {
        return;
      }

      if (!health) {
        setStatus("starting");
        setStatusCode(null);
        return;
      }

      setStatus(health.ok ? "healthy" : "offline");
      setStatusCode(health.statusCode);
    };

    void refresh();
    const intervalId = window.setInterval(() => {
      void refresh();
    }, 5000);

    return () => {
      mounted = false;
      window.clearInterval(intervalId);
    };
  }, []);

  const label = useMemo(() => {
    if (status === "healthy") {
      return "Healthy";
    }
    if (status === "starting") {
      return "Starting";
    }
    return "Offline";
  }, [status]);

  const handleRestart = async () => {
    setIsRestarting(true);
    const ok = await restartLocalApi();
    setStatus(ok ? "starting" : "offline");
    setStatusCode(null);
    setIsRestarting(false);
  };

  if (!visible) {
    return null;
  }

  return (
    <div className="fixed bottom-4 left-4 z-90 flex items-center gap-3 rounded-lg border border-border bg-background/95 px-3 py-2 shadow-md backdrop-blur">
      <Dot status={status} />
      <div className="min-w-45">
        <p className="text-xs font-medium leading-none">Athena Engine</p>
        <p className="mt-1 text-body-sm text-muted-foreground leading-none">
          {label}
          {statusCode ? ` (${statusCode})` : ""}
        </p>
      </div>
      <Button
        variant="ghost"
        size="sm"
        className="h-7 px-2 text-body-sm"
        onClick={() => void handleRestart()}
        disabled={isRestarting}
      >
        {isRestarting ? "Restarting..." : "Restart"}
      </Button>
    </div>
  );
}
