"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);
    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>
    </div>
  );
}
