"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { Check, X, Loader2 } from "lucide-react";
import { approveUpgrade, rejectUpgrade } from "@/lib/billing/actions";

/**
 * Tiny client buttons for the admin billing list — kept in their own
 * file so the parent page stays a server component.
 */
export function ApproveButton({ requestId }: { requestId: string }) {
  const router = useRouter();
  const [pending, start] = useTransition();
  function go() {
    if (!confirm("Duyệt yêu cầu này? Người dùng sẽ được nâng lên Premium.")) return;
    start(async () => {
      const r = await approveUpgrade(requestId);
      if (!r.ok) alert("Lỗi: " + r.error);
      router.refresh();
    });
  }
  return (
    <button
      type="button"
      onClick={go}
      disabled={pending}
      className="inline-flex items-center gap-1 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-3 py-1.5 text-xs font-medium text-emerald-200 transition hover:bg-emerald-500/20 disabled:opacity-60"
    >
      {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Check className="h-3 w-3" />}
      Duyệt
    </button>
  );
}

export function RejectButton({ requestId }: { requestId: string }) {
  const router = useRouter();
  const [pending, start] = useTransition();
  function go() {
    const reason = prompt("Lý do từ chối (tuỳ chọn):", "");
    if (reason === null) return; // cancelled
    start(async () => {
      const r = await rejectUpgrade(requestId, reason || undefined);
      if (!r.ok) alert("Lỗi: " + r.error);
      router.refresh();
    });
  }
  return (
    <button
      type="button"
      onClick={go}
      disabled={pending}
      className="inline-flex items-center gap-1 rounded-md border border-rose-500/40 bg-rose-500/10 px-3 py-1.5 text-xs font-medium text-rose-200 transition hover:bg-rose-500/20 disabled:opacity-60"
    >
      {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : <X className="h-3 w-3" />}
      Từ chối
    </button>
  );
}
