"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export interface PendingPhoto {
  id: string;
  url: string;
  creditName: string | null;
  creditUrl: string | null;
  albumTitle: string;
  eventId: string | null;
}

export default function SubmissionsReview({ initial }: { initial: PendingPhoto[] }) {
  const router = useRouter();
  const [photos, setPhotos] = useState(initial);
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function decide(photo: PendingPhoto, approve: boolean) {
    setBusy(photo.id);
    setError(null);
    const prev = photos;
    setPhotos(photos.filter((p) => p.id !== photo.id));

    const res = await fetch(`/api/admin/gallery/photos/${photo.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: approve ? "approved" : "rejected" }),
    });

    setBusy(null);
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      setError(data.error || "Action failed");
      setPhotos(prev);
      return;
    }
    router.refresh();
  }

  if (!photos.length) {
    return <p className="text-sm text-be-muted">No pending submissions. 🎉</p>;
  }

  // Group by album/event so reviewers see them together.
  const groups = new Map<string, PendingPhoto[]>();
  for (const p of photos) {
    const arr = groups.get(p.albumTitle) ?? [];
    arr.push(p);
    groups.set(p.albumTitle, arr);
  }

  return (
    <div className="space-y-6">
      {error && <p className="text-sm text-red-600">{error}</p>}
      {[...groups.entries()].map(([title, items]) => (
        <div key={title} className="rounded-lg border border-be-border bg-be-surface p-4">
          <p className="mb-3 text-sm font-medium">
            {title} <span className="text-be-muted">· {items.length} pending</span>
          </p>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
            {items.map((p) => (
              <div key={p.id} className="overflow-hidden rounded-md border border-be-border">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={p.url} alt="" className="aspect-square w-full object-cover" />
                <div className="p-2">
                  <p className="truncate text-xs text-be-muted">
                    {p.creditName ? (
                      p.creditUrl ? (
                        <a href={p.creditUrl} target="_blank" rel="noopener noreferrer" className="hover:underline">
                          📷 {p.creditName}
                        </a>
                      ) : (
                        <>📷 {p.creditName}</>
                      )
                    ) : (
                      "No credit"
                    )}
                  </p>
                  <div className="mt-2 flex gap-2">
                    <button
                      onClick={() => decide(p, true)}
                      disabled={busy === p.id}
                      className="flex-1 rounded bg-green-600 px-2 py-1 text-xs font-medium text-white hover:bg-green-700 disabled:opacity-50"
                    >
                      Approve
                    </button>
                    <button
                      onClick={() => decide(p, false)}
                      disabled={busy === p.id}
                      className="flex-1 rounded bg-be-surface-2 px-2 py-1 text-xs font-medium text-be-text hover:bg-be-border disabled:opacity-50"
                    >
                      Reject
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}
