"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { Play, RefreshCw, Square, Trash2 } from "lucide-react";
import { Button } from "@/components/ui";

export function InstanceActions({ instance_id }: { instance_id: number | string }) {
  const router = useRouter();
  const [loading, setLoading] = useState<string | null>(null);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  const id = typeof instance_id === "number" ? instance_id.toString() : instance_id;

  async function run(action: "deploy" | "start" | "stop") {
    setLoading(action);
    await fetch(`/api/instances/${id}/action`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ action })
    });
    setLoading(null);
    router.refresh();
  }

  async function deleteInstance() {
    if (!confirm("Are you sure you want to delete this instance? This action cannot be undone.")) {
      return;
    }

    setLoading("delete");
    const response = await fetch(`/api/instances/${id}`, {
      method: "DELETE"
    });

    if (response.ok) {
      router.refresh();
    } else {
      alert("Failed to delete instance");
      setLoading(null);
    }
  }

  if (showDeleteConfirm) {
    return (
      <div className="flex flex-wrap gap-2">
        <Button variant="secondary" onClick={() => setShowDeleteConfirm(false)}>
          Cancel
        </Button>
        <Button variant="danger" onClick={deleteInstance} disabled={loading === "delete"}>
          <Trash2 size={15} />
          {loading === "delete" ? "..." : "Confirm Delete"}
        </Button>
      </div>
    );
  }

  return (
    <div className="flex flex-wrap gap-2">
      <Button variant="secondary" onClick={() => run("deploy")} disabled={loading !== null}>
        <RefreshCw size={15} />
        {loading === "deploy" ? "..." : "Deploy"}
      </Button>
      <Button variant="secondary" onClick={() => run("start")} disabled={loading !== null}>
        <Play size={15} />
        Start
      </Button>
      <Button variant="secondary" onClick={() => run("stop")} disabled={loading !== null}>
        <Square size={15} />
        Stop
      </Button>
      <Button variant="danger" onClick={() => setShowDeleteConfirm(true)} disabled={loading !== null}>
        <Trash2 size={15} />
        Delete
      </Button>
    </div>
  );
}
