"use client";

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

interface Props {
  id: string;
  currentStatus: string;
}

export default function ReviewActions({ id, currentStatus }: Props) {
  const [note, setNote] = useState("");
  const [pending, startTransition] = useTransition();
  const [err, setErr] = useState<string | null>(null);
  const router = useRouter();

  async function act(action: "approve" | "reject" | "needs_human") {
    setErr(null);
    const res = await fetch(`/api/admin/review-queue/${id}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ action, note }),
    });
    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      setErr(body.error || `HTTP ${res.status}`);
      return;
    }
    startTransition(() => {
      router.refresh();
      router.push("/admin/review-queue");
    });
  }

  return (
    <div className="rounded border border-[#1f2937] bg-[#0b0f17] p-4">
      <div className="text-xs uppercase tracking-wider text-[#9ca3af] mb-2">
        Current status: <span className="text-[#e5e7eb]">{currentStatus}</span>
      </div>
      <textarea
        value={note}
        onChange={(e) => setNote(e.target.value)}
        placeholder="Reviewer note (optional)"
        className="w-full rounded border border-[#1f2937] bg-[#070a10] p-2 text-sm text-[#e5e7eb] focus:border-[#1D4ED8] focus:outline-none"
        rows={2}
      />
      <div className="mt-3 flex flex-wrap gap-3 text-sm">
        <button
          onClick={() => act("approve")}
          disabled={pending}
          className="rounded bg-[#059669] px-4 py-2 font-medium text-white hover:bg-[#10b981] disabled:opacity-50"
        >
          Approve & publish
        </button>
        <button
          onClick={() => act("needs_human")}
          disabled={pending}
          className="rounded bg-[#b45309] px-4 py-2 font-medium text-white hover:bg-[#d97706] disabled:opacity-50"
        >
          Needs human rewrite
        </button>
        <button
          onClick={() => act("reject")}
          disabled={pending}
          className="rounded bg-[#b91c1c] px-4 py-2 font-medium text-white hover:bg-[#dc2626] disabled:opacity-50"
        >
          Reject
        </button>
      </div>
      {err && <div className="mt-2 text-xs text-[#fca5a5]">{err}</div>}
    </div>
  );
}
