"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";

export default function DeviceActions({ deviceId, state }: { deviceId: string; state: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  async function act(action: "AUTHORIZE" | "REVOKE" | "DISABLE") {
    setLoading(true);
    try {
      await fetch(`/api/devices/${deviceId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action }),
      });
      router.refresh();
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex gap-2 justify-end">
      {state !== "AUTHORIZED" && (
        <button
          disabled={loading}
          onClick={() => act("AUTHORIZE")}
          className="text-emerald-400 hover:text-emerald-300 text-xs"
        >
          Authorize
        </button>
      )}
      {state !== "REVOKED" && (
        <button disabled={loading} onClick={() => act("REVOKE")} className="text-red-400 hover:text-red-300 text-xs">
          Revoke
        </button>
      )}
    </div>
  );
}
