import type { Prisma } from '@prisma/client';
import { redirect } from 'next/navigation';
import { PAYMENTS_ENABLED } from '@/lib/features';
import { prisma } from '@/lib/prisma';
import { requireRole } from '@/lib/auth/dal';
import { EmptyState, PageHeader, Pager, Panel, ShellPage, StatGrid } from '@/components/layout/DashboardPage';
import { OrderStatusPill } from '@/components/account/OrderStatusPill';
import { INTL_LOCALE } from '@/i18n/config';
import { getLocale, getMessages } from '@/i18n/server';
import { cn } from '@/lib/cn';

const PAGE_SIZE = 50;
const STATUSES = ['PAID', 'PENDING', 'FAILED', 'EXPIRED'] as const;
type Status = (typeof STATUSES)[number];

export default async function TransactionsPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  await requireRole(['SUPER_ADMIN'], '/admin/transaksi');
  if (!PAYMENTS_ENABLED) redirect('/admin');
  const locale = await getLocale();
  const all = await getMessages();
  const t = all.dash.adminOrders;
  const o = all.dash.orders;
  const c = all.dash.common;
  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 sp = await searchParams;
  const status = STATUSES.includes(sp.status as Status) ? (sp.status as Status) : undefined;
  const page = Math.max(1, Number(sp.hal) || 1);
  const where: Prisma.OrderWhereInput = status ? { status } : {};

  const [total, rows, counts, revenue] = await Promise.all([
    prisma.order.count({ where }),
    prisma.order.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
      select: {
        id: true,
        providerRef: true,
        amount: true,
        status: true,
        referralCode: true,
        paymentType: true,
        createdAt: true,
        user: { select: { name: true, email: true } },
      },
    }),
    prisma.order.groupBy({ by: ['status'], _count: { _all: true } }),
    prisma.order.aggregate({ where: { status: 'PAID' }, _sum: { amount: true } }),
  ]);
  const countOf = (s: Status) => counts.find((x) => x.status === s)?._count._all ?? 0;
  const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  const href = (s: Status | undefined, hal = 1) => {
    const p = new URLSearchParams();
    if (s) p.set('status', s);
    if (hal > 1) p.set('hal', String(hal));
    const str = p.toString();
    return str ? `/admin/transaksi?${str}` : '/admin/transaksi';
  };

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

      <StatGrid
        className="mt-8"
        stats={[
          { label: t.totals.revenue, value: money(revenue._sum.amount ?? 0) },
          { label: t.totals.paid, value: countOf('PAID') },
          { label: t.totals.pending, value: countOf('PENDING') },
        ]}
      />

      <nav className="no-scrollbar -mx-1 mt-8 flex gap-1 overflow-x-auto">
        {[undefined, ...STATUSES].map((s) => (
          <a
            key={s ?? 'all'}
            href={href(s)}
            aria-current={status === s ? 'page' : undefined}
            className={cn(
              'rounded-full px-3.5 py-1.5 text-[13px] font-medium whitespace-nowrap transition-colors',
              status === s ? 'bg-ink text-white' : 'text-muted hover:text-ink',
            )}
          >
            {s ? o.status[s] : c.all}{' '}
            <span className="opacity-60 tabular-nums">{s ? countOf(s) : counts.reduce((a, x) => a + x._count._all, 0)}</span>
          </a>
        ))}
      </nav>

      <Panel className="mt-4">
        {rows.length === 0 ? (
          <EmptyState text={t.empty} />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[760px] text-left text-sm">
              <thead className="border-b border-line text-[12px] text-subtle">
                <tr>
                  {[o.cols.buyer, o.cols.ref, o.cols.amount, o.cols.referral, o.cols.date, o.cols.status].map((h) => (
                    <th key={h} scope="col" className="px-5 py-3 font-medium">
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-line">
                {rows.map((r) => (
                  <tr key={r.id}>
                    <td className="px-5 py-3.5">
                      <p className="font-semibold text-ink">{r.user.name}</p>
                      <p className="text-xs text-muted">{r.user.email}</p>
                    </td>
                    <td className="px-5 py-3.5 font-mono text-xs text-ink-soft">
                      {r.providerRef}
                      {r.paymentType && <span className="block font-sans text-subtle">{r.paymentType}</span>}
                    </td>
                    <td className="px-5 py-3.5 font-medium text-ink tabular-nums">{money(r.amount)}</td>
                    <td className="px-5 py-3.5 text-ink-soft">{r.referralCode ?? <span className="text-subtle">—</span>}</td>
                    <td className="px-5 py-3.5 text-muted tabular-nums">{timeFmt.format(r.createdAt)}</td>
                    <td className="px-5 py-3.5">
                      <OrderStatusPill status={r.status} label={o.status[r.status]} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Panel>
      <Pager page={page} pages={pages} href={(n) => href(status, n)} labels={c} />
    </ShellPage>
  );
}
