import Link from 'next/link';
import { notFound, redirect } from 'next/navigation';
import { getCurrentCustomer } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

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 AccountOrderDetailPage({ params }: { params: { id: string } }) {
  const customer = await getCurrentCustomer();
  if (!customer) redirect('/account/login');

  const order = await prisma.order.findUnique({
    where: { id: params.id },
    include: { items: true },
  });
  if (!order || order.customerId !== customer.id) notFound();

  const shipping = order.shippingAddress ? JSON.parse(order.shippingAddress) : null;

  return (
    <div className="mx-auto max-w-3xl px-6 py-12">
      <Link href="/account" className="tag-label text-muted hover:text-clay">
        ← My account
      </Link>
      <div className="mt-4 flex items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">Order</h1>
        <span className={`tag-label rounded-full px-3 py-1 ${statusClasses(order.status)}`}>{statusLabel(order.status)}</span>
      </div>

      <div className="mt-6 grid gap-6 border border-line bg-surface p-6 sm:grid-cols-2">
        <div>
          <p className="tag-label mb-1">Placed</p>
          <p className="text-sm">
            {new Date(order.createdAt).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}
          </p>
        </div>
        {shipping && (
          <div className="sm:col-span-2">
            <p className="tag-label mb-1">Shipping address</p>
            <p className="text-sm">
              {shipping.name}
              <br />
              {[shipping.address?.line1, shipping.address?.line2].filter(Boolean).join(', ')}
              <br />
              {[shipping.address?.city, shipping.address?.postal_code].filter(Boolean).join(', ')}
              <br />
              {shipping.address?.country}
            </p>
          </div>
        )}
      </div>

      <div className="mt-10 divide-y divide-line border-t border-line">
        {order.items.map((item) => (
          <div key={item.id} className="flex flex-wrap items-center justify-between gap-4 py-6">
            <img
              src={item.placementPreviewUrl || item.designPreviewUrl}
              alt={item.productName}
              className="h-24 w-24 border border-line bg-paper object-contain"
            />
            <div className="flex-1">
              <p className="font-display text-lg">{item.productName}</p>
              <p className="text-sm text-muted">
                {item.color}
                {item.size ? `, ${item.size}` : ''} · qty {item.quantity}
              </p>
            </div>
            <p className="font-mono text-sm">{formatPrice(item.unitPrice * item.quantity)}</p>
          </div>
        ))}
      </div>

      <div className="mt-6 flex justify-end">
        <div className="flex items-baseline gap-3">
          <span className="tag-label">Total</span>
          <span className="font-mono text-xl">{formatPrice(order.total)}</span>
        </div>
      </div>
    </div>
  );
}
