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 { deleteExpense } from './actions';

export default async function ExpensesPage() {
  const expenses = await prisma.expense.findMany({
    orderBy: { date: 'desc' },
  });

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <AdminNav />
      <div className="flex items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">Expenses</h1>
        <Link
          href="/admin/accounts/expenses/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Record an expense
        </Link>
      </div>
      <AccountsNav active="/admin/accounts/expenses" />
      <p className="mt-4 text-sm text-muted">
        Every expense that reduces profit. Auto-created from supplier invoices, plus manual entries for postage, utilities, and other costs.
      </p>

      {expenses.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No expenses recorded yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {expenses.map((e) => (
            <div key={e.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">
                {e.date.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">{e.description}</p>
                <p className="truncate text-xs text-muted">{e.category}</p>
              </div>
              {e.receiptFileName && <span className="tag-label hidden text-muted sm:inline">Receipt</span>}
              <span className="w-20 shrink-0 text-right font-mono text-sm">
                <Price cents={e.amount} />
              </span>
              {e.receiptDataUrl && (
                <Link href={`/admin/accounts/expenses/${e.id}`} className="tag-label text-muted hover:text-ink">
                  View
                </Link>
              )}
              <form action={deleteExpense}>
                <input type="hidden" name="id" value={e.id} />
                <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                  Delete
                </button>
              </form>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
