"use client";

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

export function BoostActions({
  packageId,
  isActive,
}: {
  packageId: number;
  isActive: boolean;
}) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  async function toggleActive() {
    setLoading(true);
    try {
      const res = await fetch("/api/admin/boosts", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ package_id: packageId, is_active: !isActive }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data.error || "Failed to update package");
      } else {
        router.refresh();
      }
    } catch {
      alert("Failed to update package");
    } finally {
      setLoading(false);
    }
  }

  return (
    <button
      disabled={loading}
      onClick={toggleActive}
      className={`px-3 py-1 rounded text-xs disabled:opacity-50 ${
        isActive
          ? "bg-red-600 hover:bg-red-700 text-white"
          : "bg-green-600 hover:bg-green-700 text-white"
      }`}
    >
      {loading ? "..." : isActive ? "Deactivate" : "Activate"}
    </button>
  );
}
