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 ExpenseDetailPage({ params }: { params: { id: string } }) {
  const expense = await prisma.expense.findUnique({ where: { id: params.id } });
  if (!expense) notFound();

  const isPdf = expense.receiptDataUrl?.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">{expense.description}</h1>
        <span className="font-mono text-sm text-muted">
          {expense.date.toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' })}
        </span>
      </div>

      <div className="mt-6 space-y-2 border-t border-line py-4">
        <p className="text-sm">
          <span className="text-muted">Category:</span> {expense.category}
        </p>
        <p className="font-mono text-lg">
          <Price cents={expense.amount} />
        </p>
        {expense.notes && <p className="border-l-2 border-splash-orange pl-4 text-sm italic">{expense.notes}</p>}
      </div>

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

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