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

export default async function InboxPage() {
  const proofs = await prisma.designProof.findMany({
    include: {
      product: true,
      messages: { orderBy: { createdAt: 'desc' }, take: 1 },
    },
  });

  // Only show threads that actually have at least one message, most recent first.
  const withMessages = proofs
    .filter((p) => p.messages.length > 0)
    .sort((a, b) => b.messages[0].createdAt.getTime() - a.messages[0].createdAt.getTime());

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

      {withMessages.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No conversations yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {withMessages.map((p) => {
            const last = p.messages[0];
            return (
              <Link
                key={p.id}
                href={`/admin/inbox/${p.id}`}
                className="flex items-center gap-4 py-4 hover:bg-surface"
              >
                <img src={p.imageDataUrl} alt="" className="h-14 w-14 border border-line object-cover" />
                <div className="flex-1">
                  <p className="font-medium">{p.customerName || p.customerEmail}</p>
                  <p className="truncate text-sm text-muted">
                    {last.sender === 'ADMIN' ? 'You: ' : ''}
                    {last.body}
                  </p>
                </div>
                <span className="tag-label">{p.product.name}</span>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
