import { prisma } from '@/lib/prisma';
import { redirect } from 'next/navigation';
import { PAYMENTS_ENABLED } from '@/lib/features';
import { requireUser } from '@/lib/auth/dal';
import { PREMIUM_PRICE } from '@/lib/payments/midtrans';
import { BuyPremiumButton } from '@/components/affiliate/AffiliateClient';
import { OrderStatusPill } from '@/components/account/OrderStatusPill';
import { EmptyState, PageHeader, Panel, ShellPage } from '@/components/layout/DashboardPage';
import { INTL_LOCALE } from '@/i18n/config';
import { getLocale, getMessages } from '@/i18n/server';

export default async function OrdersPage() {
  const user = await requireUser('/akun/pesanan');
  if (!PAYMENTS_ENABLED) redirect('/akun');
  const locale = await getLocale();
  const all = await getMessages();
  const t = all.dash.orders;
  const intl = INTL_LOCALE[locale];
  const money = (n: number) => all.affiliate.price(n.toLocaleString(intl));
  const timeFmt = new Intl.DateTimeFormat(intl, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });

  const orders = await prisma.order.findMany({
    where: { userId: user.id },
    orderBy: { createdAt: 'desc' },
    take: 100,
    select: { id: true, providerRef: true, amount: true, status: true, redirectUrl: true, paymentType: true, createdAt: true },
  });
  const paid = orders.some((o) => o.status === 'PAID');

  return (
    <ShellPage>
      <PageHeader eyebrow={t.eyebrow} title={t.title} text={t.text} />

      {!paid && (
        <div className="mt-8 flex flex-col gap-5 rounded-panel bg-night-950 p-6 text-white sm:flex-row sm:items-center sm:justify-between sm:p-8">
          <div>
            <p className="text-lg font-semibold">{t.buyTitle}</p>
            <p className="mt-1 max-w-lg text-sm leading-relaxed text-white/65">{t.buyText}</p>
            <p className="mt-3 text-2xl font-semibold">{money(PREMIUM_PRICE)}</p>
          </div>
          <BuyPremiumButton />
        </div>
      )}

      <Panel className="mt-6">
        {orders.length === 0 ? (
          <EmptyState text={t.empty} />
        ) : (
          <ul className="divide-y divide-line">
            {orders.map((o) => (
              <li key={o.id} className="flex flex-wrap items-center gap-x-6 gap-y-2 px-5 py-4">
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-semibold text-ink">{t.item}</p>
                  <p className="text-xs text-muted">
                    <span className="font-mono">{o.providerRef}</span> · {timeFmt.format(o.createdAt)}
                    {o.paymentType && ` · ${o.paymentType}`}
                  </p>
                </div>
                <div className="flex items-center gap-4">
                  {o.status === 'PENDING' && o.redirectUrl && (
                    <a href={o.redirectUrl} className="text-[13px] font-semibold text-accent hover:text-ink">
                      {t.continue}
                    </a>
                  )}
                  <span className="text-right">
                    <span className="block text-sm font-semibold text-ink tabular-nums">{money(o.amount)}</span>
                    <OrderStatusPill status={o.status} label={t.status[o.status]} />
                  </span>
                </div>
              </li>
            ))}
          </ul>
        )}
      </Panel>
    </ShellPage>
  );
}
