import Link from 'next/link';
import { prisma } from '@/lib/db';
import { PLANS, planById } from '@/lib/plans';
import { AHead, Filters, Pager, Stat, fieldSm } from '@/components/admin/ui';
import { PAGE, PAY_TR as ST, dt, href, n, page, tryFmt } from '@/lib/admin';
import { paymentWhere, type PaySP } from '@/lib/adminQuery';


export default async function Payments({ searchParams }: { searchParams: Promise<PaySP> }) {
  const sp = await searchParams; const pg = page(sp.page);
  const where = paymentWhere(sp);
  const real = { ...where, plan: sp.p ? where.plan : { not: 'admin' } };
  const [rows, total, sum, byStatus, stalePending] = await Promise.all([
    prisma.payment.findMany({ where, orderBy: { createdAt: 'desc' }, skip: (pg - 1) * PAGE, take: PAGE, include: { user: { select: { email: true, name: true, company: true } }, order: { select: { id: true, code: true, status: true } } } }),
    prisma.payment.count({ where }),
    prisma.payment.aggregate({ where: { ...real, status: 'succeeded' }, _sum: { amount: true, credits: true }, _count: true }),
    prisma.payment.groupBy({ by: ['status'], where: real, _count: true }),
    prisma.payment.count({ where: { status: 'pending', plan: { not: 'admin' }, createdAt: { lt: new Date(Date.now() - 2 * 3600_000) } } }),
  ]);
  const c = (k: string) => byStatus.find((x) => x.status === k)?._count ?? 0;
  const params = sp as Record<string, string | undefined>;
  return (
    <div className="space-y-3">
      <AHead kicker="Yönetim" title="Ödemeler">
        <a href={href('/api/krtf1krtf/export', { ...params, page: undefined }, { type: 'payments' })} className="btn-line btn-sm">CSV indir</a>
      </AHead>
      <div className="grid grid-cols-2 gap-2 md:grid-cols-4">
        <Stat k="Tahsilat (filtre)" v={tryFmt(sum._sum.amount ?? 0)} sub={`${n(sum._count)} başarılı ödeme · ${n(sum._sum.credits ?? 0)} kredi`} tone="good" />
        <Stat k="Başarısız / iptal" v={n(c('failed'))} tone={c('failed') ? 'bad' : undefined} href={href('/krtf1krtf/odemeler', params, { s: 'failed', page: undefined })} />
        <Stat k="Bekleyen" v={n(c('pending'))} sub="checkout açılmış, sonuç gelmemiş" href={href('/krtf1krtf/odemeler', params, { s: 'pending', page: undefined })} />
        <Stat k="2 saati geçen bekleyen" v={n(stalePending)} sub="çoğu terk edilmiş checkout" tone={stalePending ? 'warn' : undefined} />
      </div>
      <Filters reset="/krtf1krtf/odemeler">
        <label className="flex flex-col"><span className="label">Ara</span><input name="q" defaultValue={sp.q} placeholder="e-posta, sipariş kodu, Dodo kimliği" className={`${fieldSm} w-64`} /></label>
        <label className="flex flex-col"><span className="label">Durum</span><select name="s" defaultValue={sp.s || ''} className={fieldSm}><option value="">Tümü</option>{Object.entries(ST).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></label>
        <label className="flex flex-col"><span className="label">Paket</span><select name="p" defaultValue={sp.p || ''} className={fieldSm}><option value="">Tümü</option>{PLANS.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}<option value="admin">Yönetici tanımı</option></select></label>
        <label className="flex flex-col"><span className="label">Başlangıç</span><input type="date" name="from" defaultValue={sp.from} className={fieldSm} /></label>
        <label className="flex flex-col"><span className="label">Bitiş</span><input type="date" name="to" defaultValue={sp.to} className={fieldSm} /></label>
      </Filters>
      <div className="overflow-x-auto bg-white">
        <table className="w-full min-w-[900px] text-left text-[13px]">
          <thead className="border-b border-ink/15"><tr className="[&>th]:tag [&>th]:px-3 [&>th]:py-2"><th>Tarih</th><th>Kullanıcı</th><th>Paket</th><th className="text-right">Kredi</th><th className="text-right">Tutar</th><th>Durum</th><th>Sipariş</th><th>Dodo</th></tr></thead>
          <tbody>
            {rows.map((p) => (
              <tr key={p.id} className="border-b border-ink/5 hover:bg-paper-2 [&>td]:px-3 [&>td]:py-2">
                <td className="num whitespace-nowrap text-[12px]">{dt(p.createdAt)}</td>
                <td><Link href={`/krtf1krtf/kullanicilar/${p.userId}`} className="hover:underline">{p.user.company || p.user.name}</Link><div className="text-[12px] text-ink-soft">{p.user.email}</div></td>
                <td>{p.plan === 'admin' ? <span className="bg-paper-3 px-1">yönetici tanımı</span> : planById(p.plan)?.name || p.plan}</td>
                <td className="num text-right">{p.credits}</td>
                <td className="num text-right font-semibold">{tryFmt(p.amount, p.currency)}</td>
                <td><span className={`px-1.5 py-0.5 text-[11.5px] font-semibold ${p.status === 'succeeded' ? 'bg-ok text-white' : p.status === 'failed' ? 'bg-survey text-white' : 'bg-paper-3'}`}>{ST[p.status] || p.status}</span></td>
                <td>{p.order ? <Link href={`/krtf1krtf/siparisler/${p.order.id}`} className="font-mono text-[12px] hover:underline">{p.order.code}</Link> : <span className="text-ink-soft">kredi paketi</span>}</td>
                <td className="max-w-[180px] truncate font-mono text-[11px] text-ink-soft" title={p.dodoPaymentId || p.dodoSessionId || ''}>{p.dodoPaymentId || p.dodoSessionId || ''}</td>
              </tr>
            ))}
            {!rows.length && <tr><td colSpan={8} className="px-3 py-6 text-center text-ink-soft">Bu filtreye uyan ödeme yok.</td></tr>}
          </tbody>
        </table>
      </div>
      <Pager page={pg} total={total} size={PAGE} link={(p) => href('/krtf1krtf/odemeler', params, { page: p })} />
    </div>
  );
}
