"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { resolveRequest } from "./actions";
import { Check, X } from "lucide-react";

export function RequestActions({ requestId }: { requestId: string }) {
  const router = useRouter();
  const [pending, setPending] = useState<"approve" | "deny" | null>(null);
  const [error, setError] = useState("");

  async function handle(decision: "APPROVED" | "DENIED") {
    setPending(decision === "APPROVED" ? "approve" : "deny");
    setError("");
    const result = await resolveRequest(requestId, decision);
    setPending(null);
    if ("error" in result) setError(result.error);
    else router.refresh();
  }

  return (
    <div className="flex items-center gap-2 shrink-0">
      {error && <span className="text-xs text-danger-700">{error}</span>}
      <button
        onClick={() => handle("DENIED")}
        disabled={!!pending}
        className="inline-flex items-center gap-1.5 rounded-lg border border-danger-200 bg-white px-3 py-1.5 text-sm font-medium text-danger-700 hover:bg-danger-50 disabled:opacity-50 transition-colors"
      >
        <X className="h-3.5 w-3.5" />
        {pending === "deny" ? "Denying…" : "Deny"}
      </button>
      <button
        onClick={() => handle("APPROVED")}
        disabled={!!pending}
        className="inline-flex items-center gap-1.5 rounded-lg bg-success px-3 py-1.5 text-sm font-semibold text-white hover:opacity-90 disabled:opacity-50 transition-opacity"
      >
        <Check className="h-3.5 w-3.5" />
        {pending === "approve" ? "Approving…" : "Approve"}
      </button>
    </div>
  );
}
