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

export default async function PurchaseDetailPage({ params }: { params: { id: string } }) {
  const purchase = await prisma.purchase.findUnique({
    where: { id: params.id },
    include: { items: { include: { product: true } } },
  });
  if (!purchase) notFound();

  const isPdf = purchase.invoiceDataUrl?.startsWith('data:application/pdf');

  return (
    <div className="mx-auto max-w-2xl px-6 py-12">
      <AdminNav />
      <div className="flex items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">{purchase.supplierName}</h1>
        <span className="font-mono text-sm text-muted">
          {purchase.purchasedAt.toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' })}
        </span>
      </div>

      <div className="mt-8 divide-y divide-line border-t border-line">
        {purchase.items.map((item) => (
          <div key={item.id} className="flex flex-wrap items-center gap-x-4 gap-y-1 py-3">
            <div className="min-w-0 flex-1">
              <p className="text-sm font-medium">{item.description}</p>
              <p className="text-xs text-muted">
                {item.productId
                  ? [item.color, item.size].filter(Boolean).join(' · ') || 'Stock item'
                  : 'Material / other — not stock-counted'}
              </p>
            </div>
            <span className="font-mono text-xs text-muted">
              {item.quantity} × <Price cents={item.unitCost} />
            </span>
            <span className="w-20 shrink-0 text-right font-mono text-sm">
              <Price cents={item.quantity * item.unitCost} />
            </span>
          </div>
        ))}
      </div>

      <p className="mt-4 text-right font-mono text-lg">
        Total <Price cents={purchase.total} />
      </p>

      {purchase.notes && <div className="mt-6 border-l-2 border-splash-orange pl-4 text-sm italic">{purchase.notes}</div>}

      {purchase.invoiceDataUrl && (
        <div className="mt-8">
          <p className="tag-label mb-3">Invoice{purchase.invoiceFileName ? ` — ${purchase.invoiceFileName}` : ''}</p>
          {isPdf ? (
            <iframe src={purchase.invoiceDataUrl} title="Invoice" className="h-[600px] w-full border border-line" />
          ) : (
            <img
              src={purchase.invoiceDataUrl}
              alt="Invoice"
              className="max-h-[600px] w-full border border-line object-contain"
            />
          )}
          <a
            href={purchase.invoiceDataUrl}
            download={purchase.invoiceFileName ?? 'invoice'}
            className="mt-2 inline-block tag-label text-clay hover:text-clay-dark"
          >
            Download invoice
          </a>
        </div>
      )}

      <Link href="/admin/accounts/purchases" className="mt-8 inline-block tag-label hover:text-ink">
        ← All purchases
      </Link>
    </div>
  );
}
