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

export default async function PurchasesPage() {
  const purchases = await prisma.purchase.findMany({
    include: { items: true },
    orderBy: { purchasedAt: 'desc' },
  });

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <AdminNav />
      <div className="flex flex-wrap items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">Purchases</h1>
        <Link
          href="/admin/accounts/purchases/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Record a purchase
        </Link>
      </div>
      <AccountsNav active="/admin/accounts/purchases" />
      <p className="mt-4 text-sm text-muted">
        Stock coming in from suppliers, with the invoice attached. Product lines add to stock
        counts automatically; deleting a purchase takes them back out.
      </p>

      {purchases.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No purchases recorded yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {purchases.map((p) => (
            <div key={p.id} className="flex flex-wrap items-center gap-x-4 gap-y-1 py-4">
              <span className="w-24 shrink-0 font-mono text-xs text-muted">
                {p.purchasedAt.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}
              </span>
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-medium">{p.supplierName}</p>
                <p className="truncate text-xs text-muted">
                  {p.items.map((i) => `${i.quantity}× ${i.description}`).join(', ')}
                </p>
              </div>
              {p.invoiceDataUrl && <span className="tag-label hidden text-muted sm:inline">Invoice attached</span>}
              <span className="w-20 shrink-0 text-right font-mono text-sm">
                <Price cents={p.total} />
              </span>
              <Link href={`/admin/accounts/purchases/${p.id}`} className="tag-label text-muted hover:text-ink">
                View
              </Link>
              <form action={deletePurchase}>
                <input type="hidden" name="id" value={p.id} />
                <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                  Delete
                </button>
              </form>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
