import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import { deleteRequest } from './actions';

export default async function CustomRequestsPage() {
  const rows = await prisma.customRequest.findMany({
    include: { product: true },
    orderBy: { createdAt: 'desc' },
  });

  // NEW requests first, most recent within each group (Array.sort is stable).
  const requests = [...rows].sort((a, b) => (a.status === b.status ? 0 : a.status === 'NEW' ? -1 : 1));

  return (
    <div className="mx-auto max-w-3xl px-6 py-12">
      <AdminNav />
      <h1 className="font-display text-3xl">Photo requests</h1>

      {requests.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No photo requests yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {requests.map((r) => (
            <div key={r.id} className="flex items-center gap-4 py-4 hover:bg-surface">
              <Link href={`/admin/custom-requests/${r.id}`} className="flex flex-1 items-center gap-4">
                <img src={r.imageDataUrl} alt="" className="h-14 w-14 border border-line object-cover" />
                <div className="flex-1">
                  <p className="font-medium">{r.customerName}</p>
                  <p className="truncate text-sm text-muted">{r.customerEmail}</p>
                </div>
                <span className="tag-label">{r.product.name}</span>
                <span
                  className={`tag-label rounded-full px-3 py-1 ${
                    r.status === 'NEW' ? 'bg-splash-orange/10 text-splash-orange' : 'bg-splash-blue/10 text-splash-blue'
                  }`}
                >
                  {r.status}
                </span>
              </Link>
              <form action={deleteRequest}>
                <input type="hidden" name="id" value={r.id} />
                <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                  Delete
                </button>
              </form>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
