"use client";

import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

type Report = {
  id: string;
  targetType: "recipe" | "comment" | "user";
  targetId: string;
  reason: string;
  createdAt: string;
  reporterName: string;
  reporterEmail: string;
};

export function ReportsQueue({ reports }: { reports: Report[] }) {
  const router = useRouter();

  async function resolve(id: string, status: "reviewed" | "dismissed") {
    const res = await fetch(`/api/v1/admin/reports/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    if (!res.ok) {
      toast.error("Failed to update report");
      return;
    }
    toast.success(status === "reviewed" ? "Marked reviewed" : "Dismissed");
    router.refresh();
  }

  if (reports.length === 0) {
    return <p className="text-muted-foreground text-sm">No pending reports.</p>;
  }

  return (
    <div className="space-y-3">
      {reports.map((r) => (
        <div key={r.id} className="rounded-lg border p-4 space-y-2">
          <div className="flex items-start justify-between gap-4">
            <div className="space-y-1">
              <div className="flex items-center gap-2">
                <Badge variant="outline" className="capitalize">{r.targetType}</Badge>
                <span className="text-xs text-muted-foreground font-mono">{r.targetId}</span>
              </div>
              <p className="text-sm">{r.reason}</p>
              <p className="text-xs text-muted-foreground">
                Reported by {r.reporterName} ({r.reporterEmail}) · {new Date(r.createdAt).toLocaleString()}
              </p>
            </div>
            <div className="flex gap-2 shrink-0">
              <Button size="sm" variant="outline" onClick={() => { void resolve(r.id, "dismissed"); }}>
                Dismiss
              </Button>
              <Button size="sm" onClick={() => { void resolve(r.id, "reviewed"); }}>
                Mark reviewed
              </Button>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
