import Link from 'next/link';
import { redirect } from 'next/navigation';
import { getCurrentCustomer } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { logoutCustomer } from './actions';

function formatPrice(cents: number) {
  return `£${(cents / 100).toFixed(2)}`;
}

function statusLabel(status: string) {
  if (status === 'PAID') return 'Confirmed';
  if (status === 'FAILED') return 'Failed';
  return 'Processing';
}

function statusClasses(status: string) {
  if (status === 'PAID') return 'bg-splash-blue/10 text-splash-blue';
  if (status === 'FAILED') return 'bg-splash-pink/10 text-splash-pink';
  return 'bg-splash-orange/10 text-splash-orange';
}

export default async function AccountPage() {
  const customer = await getCurrentCustomer();
  if (!customer) redirect('/account/login');

  const orders = await prisma.order.findMany({
    where: { customerId: customer.id },
    orderBy: { createdAt: 'desc' },
    include: { items: true },
  });

  return (
    <div className="mx-auto max-w-3xl px-6 py-12">
      <div className="flex items-baseline justify-between gap-3">
        <div>
          <h1 className="font-display text-3xl">My account</h1>
          <p className="mt-1 text-sm text-muted">
            {customer.name ? `${customer.name} · ` : ''}
            {customer.email}
          </p>
        </div>
        <form action={logoutCustomer}>
          <button
            type="submit"
            className="tag-label border border-line px-3 py-1.5 hover:border-clay hover:text-clay"
          >
            Log out
          </button>
        </form>
      </div>

      <h2 className="mt-10 font-display text-xl">Order history</h2>
      {orders.length === 0 ? (
        <p className="mt-3 text-sm text-muted">No orders yet.</p>
      ) : (
        <div className="mt-4 divide-y divide-line border-t border-line">
          {orders.map((order) => (
            <Link
              key={order.id}
              href={`/account/orders/${order.id}`}
              className="flex flex-wrap items-center justify-between gap-2 py-4 hover:bg-surface"
            >
              <div>
                <p className="text-sm">
                  {new Date(order.createdAt).toLocaleDateString(undefined, { dateStyle: 'medium' })} ·{' '}
                  {order.items.length} item{order.items.length === 1 ? '' : 's'}
                </p>
                <span className={`tag-label mt-1 inline-block rounded-full px-3 py-1 ${statusClasses(order.status)}`}>
                  {statusLabel(order.status)}
                </span>
              </div>
              <span className="font-mono text-sm">{formatPrice(order.total)}</span>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
