import type { Metadata } from "next";
import Link from "next/link";
import { prisma } from "@/lib/db";
import { moderatePhoto, updatePhotoAltText } from "@/lib/admin/actions";
import type { Photo, Profile, User } from "@sohbetegir/db";

export const metadata: Metadata = {
  title: "Galeri Onayları",
};

type PhotoWithUser = Photo & { user: User & { profile: Profile | null } };

const FILTERS = [
  { key: "tumu", label: "Tümü" },
  { key: "bekleyen", label: "Bekleyenler" },
  { key: "onayli", label: "Onaylılar" },
] as const;

type FilterKey = (typeof FILTERS)[number]["key"];

export default async function PhotoModerationPage({
  searchParams,
}: {
  searchParams: Promise<{ durum?: string }>;
}) {
  const { durum } = await searchParams;
  const activeFilter: FilterKey = FILTERS.some((f) => f.key === durum) ? (durum as FilterKey) : "tumu";

  const photos = await prisma.photo.findMany({
    where: { status: { in: ["PENDING", "APPROVED"] } },
    orderBy: { createdAt: "desc" },
    include: { user: { include: { profile: true } } },
  });

  const totalPending = photos.filter((p) => p.status === "PENDING").length;
  const totalApproved = photos.length - totalPending;

  const visiblePhotos = photos.filter((p) => {
    if (activeFilter === "bekleyen") return p.status === "PENDING";
    if (activeFilter === "onayli") return p.status === "APPROVED";
    return true;
  });

  const byUser = new Map<string, PhotoWithUser[]>();
  for (const photo of visiblePhotos) {
    const list = byUser.get(photo.userId);
    if (list) list.push(photo);
    else byUser.set(photo.userId, [photo]);
  }

  const groups = [...byUser.values()].sort((a, b) => {
    const aPending = a.filter((p) => p.status === "PENDING").length;
    const bPending = b.filter((p) => p.status === "PENDING").length;
    if (aPending !== bPending) return bPending - aPending;
    return b[0].createdAt.getTime() - a[0].createdAt.getTime();
  });

  return (
    <div className="p-8">
      <div className="mb-6 border-b border-border pb-6">
        <h1 className="text-[22px]">Galeri Onayları</h1>
        <p className="mt-0.5 text-[12.5px] text-text-muted">
          {totalPending} bekleyen · {totalApproved} onaylı görsel
        </p>
      </div>

      <div className="mb-6 flex gap-2">
        {FILTERS.map((filter) => {
          const count = filter.key === "bekleyen" ? totalPending : filter.key === "onayli" ? totalApproved : photos.length;
          const isActive = filter.key === activeFilter;
          return (
            <Link
              key={filter.key}
              href={filter.key === "tumu" ? "/admin/fotograf-onay" : `/admin/fotograf-onay?durum=${filter.key}`}
              className={`flex items-center gap-1.5 rounded-full border px-4 py-1.5 text-[12.5px] font-semibold transition-colors ${
                isActive ? "border-accent bg-accent text-white" : "border-border bg-surface text-text-muted hover:border-accent"
              }`}
            >
              {filter.label}
              <span
                className={`rounded-full px-1.5 py-0.5 text-[10.5px] font-bold ${
                  isActive ? "bg-white/20 text-white" : "bg-bg-alt text-text-muted"
                }`}
              >
                {count}
              </span>
            </Link>
          );
        })}
      </div>

      {groups.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-border p-8 text-center text-[13.5px] text-text-muted">
          {activeFilter === "bekleyen"
            ? "Bekleyen görsel yok."
            : activeFilter === "onayli"
              ? "Onaylı görsel yok."
              : "Henüz galeri/durum görseli yok."}
        </div>
      ) : (
        <div className="flex flex-col gap-9">
          {groups.map((group) => {
            const user = group[0].user;
            const pendingInGroup = group.filter((p) => p.status === "PENDING").length;
            const displayName = user.profile?.fullName ?? user.email;
            const initials = displayName.slice(0, 2).toUpperCase();

            return (
              <div key={user.id}>
                <div className="mb-3 flex items-center gap-2.5">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-accent to-accent-2 text-[11px] font-bold text-white">
                    {initials}
                  </div>
                  <span className="text-[14px] font-bold">{displayName}</span>
                  {pendingInGroup > 0 && (
                    <span className="rounded-full bg-accent px-2 py-0.5 text-[10.5px] font-bold text-white">
                      {pendingInGroup} bekliyor
                    </span>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
                  {group.map((photo) => {
                    const approve = moderatePhoto.bind(null, photo.id, "APPROVED");
                    const reject = moderatePhoto.bind(null, photo.id, "REJECTED");
                    const saveAlt = updatePhotoAltText.bind(null, photo.id);
                    const isPending = photo.status === "PENDING";

                    return (
                      <div key={photo.id} className="overflow-hidden rounded-2xl border border-border bg-surface">
                        <div className="relative">
                          {/* eslint-disable-next-line @next/next/no-img-element -- yerel diskten servis edilen kullanıcı içeriği */}
                          <img src={photo.url} alt={photo.altText ?? ""} className="aspect-square w-full object-cover" />
                          <span
                            className={`absolute left-1.5 top-1.5 rounded-full px-2 py-0.5 text-[10px] font-semibold ${
                              isPending ? "bg-accent/90 text-white" : "bg-green-600/90 text-white"
                            }`}
                          >
                            {isPending ? "Bekliyor" : "Onaylı"}
                          </span>
                          <span className="absolute right-1.5 top-1.5 rounded-full bg-black/50 px-2 py-0.5 text-[10px] font-semibold text-white">
                            {photo.kind === "STATUS" ? "Durum" : "Galeri"}
                          </span>
                        </div>
                        <div className="p-3">
                          <form action={saveAlt} className="mb-2 flex gap-1.5">
                            <input
                              name="altText"
                              defaultValue={photo.altText ?? ""}
                              placeholder="Alt metin"
                              className="w-full rounded-lg border border-border px-2 py-1 text-[11.5px]"
                            />
                            <button className="rounded-lg bg-bg-alt px-2 text-[11px] font-semibold text-text-muted">Kaydet</button>
                          </form>
                          {isPending ? (
                            <div className="flex gap-2">
                              <form action={approve} className="flex-1">
                                <button className="w-full rounded-lg bg-green-100 px-3 py-1.5 text-[12px] font-semibold text-green-700">
                                  Onayla
                                </button>
                              </form>
                              <form action={reject} className="flex-1">
                                <button className="w-full rounded-lg bg-accent/10 px-3 py-1.5 text-[12px] font-semibold text-accent">
                                  Reddet
                                </button>
                              </form>
                            </div>
                          ) : (
                            <form action={reject}>
                              <button className="w-full rounded-lg bg-bg-alt px-3 py-1.5 text-[12px] font-semibold text-text-muted hover:bg-border">
                                Onayı Kaldır
                              </button>
                            </form>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
