"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";

export default function InstanceActions({ instanceId, status }: { instanceId: string; status: string }) {
  const [loading, setLoading] = useState<string | null>(null);

  async function action(type: string) {
    setLoading(type);
    if (type === "delete") {
      if (!confirm("Voulez-vous vraiment supprimer cette instance ?")) {
        setLoading(null);
        return;
      }
      await fetch(`/api/instances?id=${instanceId}`, { method: "DELETE" });
    } else {
      await fetch("/api/instances", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: instanceId, action: type }),
      });
    }
    setLoading(null);
    window.location.reload();
  }

  return (
    <div className="flex gap-2">
      {status !== "running" && (
        <Button size="sm" variant="outline" onClick={() => action("start")} disabled={!!loading}>
          {loading === "start" ? "..." : "Démarrer"}
        </Button>
      )}
      {status === "running" && (
        <Button size="sm" variant="outline" onClick={() => action("stop")} disabled={!!loading}>
          {loading === "stop" ? "..." : "Arrêter"}
        </Button>
      )}
      <Button size="sm" variant="outline" onClick={() => action("reset")} disabled={!!loading}>
        {loading === "reset" ? "..." : "Réinitialiser"}
      </Button>
      <Button size="sm" variant="destructive" onClick={() => action("delete")} disabled={!!loading}>
        {loading === "delete" ? "..." : "Supprimer"}
      </Button>
    </div>
  );
}
