import Image from "next/image";
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { TYPE_LABELS, stageInfo } from "@/lib/custom-orders";
import CustomOrdersTabs from "@/components/admin/CustomOrdersTabs";

export default async function AdminCustomerUploadedImagesPage() {
  const requests = await prisma.customOrderRequest.findMany({
    where: { referenceImage: { not: null } },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Customer Uploaded Images</h1>
      <p className="mt-1 text-sm text-stone-500">Reference photos attached to custom order requests.</p>

      <CustomOrdersTabs active="/iv-manage-84x2/custom-orders/images" />

      {requests.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">
          No reference images uploaded yet — attach one when logging a request on{" "}
          <Link href="/iv-manage-84x2/custom-orders" className="text-rose-700 hover:underline">
            Customization Request
          </Link>
          .
        </p>
      ) : (
        <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4">
          {requests.map((r) => {
            const stage = stageInfo(r.status);
            return (
              <a
                key={r.id}
                href={r.referenceImage!}
                target="_blank"
                rel="noopener noreferrer"
                className="overflow-hidden rounded-lg border border-rose-100 bg-white"
              >
                <div className="relative aspect-square w-full bg-rose-50">
                  <Image src={r.referenceImage!} alt={r.customerName} fill className="object-cover" />
                </div>
                <div className="p-2">
                  <p className="truncate text-sm font-medium text-stone-800">{r.customerName}</p>
                  <p className="text-xs text-stone-500">{TYPE_LABELS[r.type] ?? r.type}</p>
                  <div className="mt-1 flex items-center justify-between">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${stage.color}`}>{stage.label}</span>
                    <span className="text-xs text-stone-400">{formatDate(r.createdAt)}</span>
                  </div>
                </div>
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
}
