import Link from 'next/link';
import { prisma } from '@/lib/db';
import { AHead, Filters, Pager, fieldSm } from '@/components/admin/ui';
import { PAGE, dt, href, n, page, tryFmt } from '@/lib/admin';
import { USER_SORT, userWhere, type UserSP } from '@/lib/adminQuery';

const F: [string, string][] = [['', 'Tümü'], ['odeyen', 'Ödeme yapan'], ['kredili', 'Kredisi olan'], ['dogrulanmamis', 'Doğrulanmamış'], ['davetli', 'Davetle gelen'], ['askida', 'Askıda'], ['admin', 'Yönetici']];

export default async function Users({ searchParams }: { searchParams: Promise<UserSP> }) {
  const sp = await searchParams; const pg = page(sp.page);
  const where = userWhere(sp);
  const [rows, total] = await Promise.all([
    prisma.user.findMany({ where, orderBy: USER_SORT[sp.o || 'yeni'] || USER_SORT.yeni, skip: (pg - 1) * PAGE, take: PAGE, include: { _count: { select: { orders: true } } } }),
    prisma.user.count({ where }),
  ]);
  const ids = rows.map((u) => u.id);
  const [spent, lastOrder] = await Promise.all([
    prisma.payment.groupBy({ by: ['userId'], where: { userId: { in: ids }, status: 'succeeded', plan: { not: 'admin' } }, _sum: { amount: true } }),
    prisma.order.groupBy({ by: ['userId'], where: { userId: { in: ids } }, _max: { createdAt: true } }),
  ]);
  const params = sp as Record<string, string | undefined>;
  return (
    <div className="space-y-3">
      <AHead kicker="Yönetim" title="Kullanıcılar">
        <a href={href('/api/krtf1krtf/export', { ...params, page: undefined }, { type: 'users' })} className="btn-line btn-sm">CSV indir</a>
      </AHead>
      <div className="flex flex-wrap gap-1">
        {F.map(([k, l]) => <Link key={k} href={href('/krtf1krtf/kullanicilar', params, { f: k, page: undefined })} className={`px-2.5 py-1.5 text-[12.5px] font-semibold ${(sp.f || '') === k ? 'bg-ink text-white' : 'bg-white hover:bg-paper-3'}`}>{l}</Link>)}
      </div>
      <Filters reset="/krtf1krtf/kullanicilar">
        {sp.f && <input type="hidden" name="f" value={sp.f} />}
        <label className="flex flex-col"><span className="label">Ara</span><input name="q" defaultValue={sp.q} placeholder="e-posta, ad, firma, telefon, davet kodu" className={`${fieldSm} w-72`} /></label>
        <label className="flex flex-col"><span className="label">Sıra</span><select name="o" defaultValue={sp.o || 'yeni'} className={fieldSm}><option value="yeni">En yeni</option><option value="eski">En eski</option><option value="kredi">En çok kredi</option><option value="siparis">En çok sipariş</option></select></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>Kullanıcı</th><th>Durum</th><th className="text-right">Kredi</th><th className="text-right">Sipariş</th><th className="text-right">Harcama</th><th>Son sipariş</th><th>Kayıt</th></tr></thead>
          <tbody>
            {rows.map((u) => (
              <tr key={u.id} className="border-b border-ink/5 hover:bg-paper-2 [&>td]:px-3 [&>td]:py-2">
                <td><Link href={`/krtf1krtf/kullanicilar/${u.id}`} className="font-bold hover:underline">{u.company || u.name}</Link><div className="text-[12px] text-ink-soft">{u.email}{u.company ? ` · ${u.name}` : ''}</div></td>
                <td className="space-x-1 text-[11px]">
                  {u.role === 'ADMIN' && <span className="bg-ink px-1 text-white">yönetici</span>}
                  {u.disabledAt && <span className="bg-survey px-1 text-white">askıda</span>}
                  {!u.emailVerifiedAt && <span className="bg-paper-3 px-1">doğrulanmadı</span>}
                  {u.referredById && <span className="bg-signal-soft px-1">davetli</span>}
                </td>
                <td className="num text-right font-bold">{u.credits}</td>
                <td className="num text-right">{n(u._count.orders)}</td>
                <td className="num text-right">{tryFmt(spent.find((x) => x.userId === u.id)?._sum.amount ?? 0)}</td>
                <td className="num whitespace-nowrap text-[12px]">{dt(lastOrder.find((x) => x.userId === u.id)?._max.createdAt)}</td>
                <td className="num whitespace-nowrap text-[12px]">{dt(u.createdAt)}</td>
              </tr>
            ))}
            {!rows.length && <tr><td colSpan={7} className="px-3 py-6 text-center text-ink-soft">Bu filtreye uyan kullanıcı yok.</td></tr>}
          </tbody>
        </table>
      </div>
      <Pager page={pg} total={total} size={PAGE} link={(p) => href('/krtf1krtf/kullanicilar', params, { page: p })} />
    </div>
  );
}
