import Link from 'next/link';
import { prisma } from '@/lib/db';
import { TEMPLATES, templateById } from '@/lib/templates';
import { PLANS, planById } from '@/lib/plans';
import { STATUS_TR } from '@/lib/orders';
import { StatusBadge } from '@/components/StatusBadge';
import { AHead, Filters, Pager, fieldSm } from '@/components/admin/ui';
import { PAGE, dt, href, page } from '@/lib/admin';
import { ORDER_SORT, orderWhere, type OrderSP } from '@/lib/adminQuery';
import { apShort } from '@/lib/ap';

export default async function Orders({ searchParams }: { searchParams: Promise<OrderSP> }) {
  const sp = await searchParams; const pg = page(sp.page);
  const where = orderWhere(sp);
  const [rows, total, counts] = await Promise.all([
    prisma.order.findMany({ where, orderBy: ORDER_SORT[sp.o || 'yeni'] || ORDER_SORT.yeni, skip: (pg - 1) * PAGE, take: PAGE, include: { user: { select: { email: true, company: true, name: true } } } }),
    prisma.order.count({ where }),
    prisma.order.groupBy({ by: ['status'], where: { ...where, status: undefined }, _count: true }),
  ]);
  const c = (k: string) => counts.find((x) => x.status === k)?._count ?? 0;
  const all = counts.reduce((a, x) => a + x._count, 0);
  const params = sp as Record<string, string | undefined>;
  return (
    <div className="space-y-3">
      <AHead kicker="Yönetim" title="Siparişler">
        <a href={href('/api/krtf1krtf/export', { ...params, page: undefined }, { type: 'orders' })} className="btn-line btn-sm">CSV indir</a>
      </AHead>
      <div className="flex flex-wrap gap-1">
        {[['', 'Tümü', all], ...Object.keys(STATUS_TR).map((k) => [k, STATUS_TR[k], c(k)])].map(([k, l, v]) => (
          <Link key={k as string} href={href('/krtf1krtf/siparisler', params, { s: k as string, page: undefined })} className={`px-2.5 py-1.5 text-[12.5px] font-semibold ${(sp.s || '') === k ? 'bg-ink text-white' : 'bg-white hover:bg-paper-3'}`}>{l} <span className="num opacity-60">{v}</span></Link>
        ))}
      </div>
      <Filters reset="/krtf1krtf/siparisler">
        {sp.s && <input type="hidden" name="s" value={sp.s} />}
        <label className="flex flex-col"><span className="label">Ara</span><input name="q" defaultValue={sp.q} placeholder="kod, e-posta, 101/5, mahalle…" className={`${fieldSm} w-60`} /></label>
        <label className="flex flex-col"><span className="label">Şablon</span><select name="t" defaultValue={sp.t || ''} className={fieldSm}><option value="">Tümü</option>{TEMPLATES.map((t) => <option key={t.id} value={t.id}>{t.name}</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>)}</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>
        <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="guncel">Son güncellenen</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>Kod</th><th>Parsel</th><th>Kullanıcı</th><th>Şablon · paket</th><th>Durum</th><th>Oluşturma</th><th>Teslim</th></tr></thead>
          <tbody>
            {rows.map((o) => (
              <tr key={o.id} className="border-b border-ink/5 hover:bg-paper-2 [&>td]:px-3 [&>td]:py-2">
                <td><Link href={`/krtf1krtf/siparisler/${o.id}`} className="font-mono font-bold underline-offset-2 hover:underline">{o.code}</Link>{o.batchId && <span className="ml-1 bg-paper-3 px-1 text-[10.5px]">toplu</span>}</td>
                <td><b>{apShort(o.ada, o.parsel)}</b><div className="text-[12px] text-ink-soft">{o.mahalle}, {o.ilce} / {o.il}</div></td>
                <td><Link href={`/krtf1krtf/kullanicilar/${o.userId}`} className="hover:underline">{o.user.company || o.user.name}</Link><div className="text-[12px] text-ink-soft">{o.user.email}</div></td>
                <td>{templateById(o.template).name}<div className="text-[12px] text-ink-soft">{planById(o.plan)?.name || o.plan} · {o.quality}</div></td>
                <td><StatusBadge s={o.status} />{o.status === 'RENDERING' && <span className="num ml-1 text-[12px]">%{o.progress}</span>}{o.claimedBy && <div className="text-[11px] text-ink-soft">ajan: {o.claimedBy}</div>}</td>
                <td className="num whitespace-nowrap text-[12px]">{dt(o.createdAt)}</td>
                <td className="num whitespace-nowrap text-[12px]">{dt(o.deliveredAt)}</td>
              </tr>
            ))}
            {!rows.length && <tr><td colSpan={7} className="px-3 py-6 text-center text-ink-soft">Bu filtreye uyan sipariş yok.</td></tr>}
          </tbody>
        </table>
      </div>
      <Pager page={pg} total={total} size={PAGE} link={(p) => href('/krtf1krtf/siparisler', params, { page: p })} />
    </div>
  );
}
