"use client";

import { motion, AnimatePresence } from "motion/react";
import { useEffect, useState } from "react";
import ActionMenu from "./action-menu";
import { invoke } from "@tauri-apps/api/core";

type App = {
  id: string;
  name: string;
  description?: string;
  address: string;
  ssh_addr?: string;
};

interface Props {
  app: App;
}

type PingStatus = "success" | "error" | "loading";

export default function AppCard({ app }: Props) {
  const [pingStatus, setPingStatus] = useState<PingStatus>("loading");
  const [hovered, setHovered] = useState(false);

  let pingColor =
    pingStatus === "success"
      ? "bg-green-500"
      : pingStatus === "error"
        ? "bg-red-500"
        : "bg-gray-500";

  const pingApp = async (): Promise<boolean> => {
    let status: boolean = await invoke("ping", { address: app.address });
    return status;
  };

  useEffect(() => {
    let isMounted = true;

    const performPing = async () => {
      setPingStatus("loading");
      try {
        // Since we simplified the Rust command to return a bool, we just read the result
        const success = await invoke<boolean>("ping", { address: app.address });
        if (isMounted) {
          setPingStatus(success ? "success" : "error");
        }
      } catch (err) {
        if (isMounted) {
          setPingStatus("error");
        }
      }
    };

    performPing();

    // Optional: Set up an interval if you want it to poll periodically
    const interval = setInterval(performPing, 10000); // Poll every 10 seconds

    return () => {
      isMounted = false;
      clearInterval(interval);
    };
  }, [app.address]);

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      className={`
        relative
        rounded-2xl
        bg-gray-100
        p-3
        ${hovered && "border bg-white"}
        transition-all
        duration-200
      `}
    >
      <div className="absolute top-4 right-4">
        <div className="relative">
          <div
            className={`absolute inset-0 rounded-full ${pingColor} animate-ping opacity-30`}
          />
          <div
            className={`relative h-2.5 w-2.5 rounded-full ${pingColor} ring-2 ring-white`}
          />
        </div>
      </div>

      <h3 className="text-2xl font-bold">{app.name}</h3>
      <a
        className={`${hovered && "text-blue-600"} transition-colors duration-200`}
        target="_blank"
        href={`http://${app.address}`}
      >
        {app.address}
      </a>

      <AnimatePresence>
        {hovered && (
          <motion.div
            initial={{ opacity: 0, y: -4 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -4 }}
            transition={{ duration: 0.15 }}
            className={`absolute bottom-3 left-3 right-3 ${app.description && "bg-white"} pt-2 flex flex-col gap-1`}
          >
            {app.description && (
              <span className="text-sm text-muted-foreground">
                {app.description}
              </span>
            )}
            <ActionMenu id={app.id} />
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
