"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";

export function CommentActions({
  commentId,
  status,
}: {
  commentId: string;
  status: string;
}) {
  const router = useRouter();
  const [deleting, setDeleting] = useState(false);

  async function updateStatus(newStatus: "APPROVED" | "REJECTED") {
    await fetch(`/api/admin/comments/${commentId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: newStatus }),
    });
    router.refresh();
  }

  async function handleDelete() {
    if (!confirm("این نظر حذف شود؟")) return;
    setDeleting(true);
    try {
      const res = await fetch(`/api/admin/comments/${commentId}`, { method: "DELETE" });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        alert(data?.error ?? "خطا در حذف نظر");
        return;
      }
      router.refresh();
    } finally {
      setDeleting(false);
    }
  }

  return (
    <div className="flex flex-wrap gap-2">
      {status !== "APPROVED" && (
        <Button variant="outline" size="sm" onClick={() => updateStatus("APPROVED")}>
          تأیید
        </Button>
      )}
      {status !== "REJECTED" && (
        <Button variant="destructive" size="sm" onClick={() => updateStatus("REJECTED")}>
          رد
        </Button>
      )}
      <Button variant="outline" size="sm" onClick={handleDelete} disabled={deleting}>
        {deleting ? "در حال حذف…" : "حذف"}
      </Button>
    </div>
  );
}
