import Link from 'next/link';
import type { OrderStatus, Prisma } from '@prisma/client';
import { prisma } from '@/lib/db';
import { requireUser } from '@/lib/auth';
import { ensureRefCode } from '@/lib/referral';
import { idsOfMahalle } from '@/lib/idari';
import { Head } from '@/components/desk/Head';
import { StatusBadge } from '@/components/StatusBadge';
import { templateById } from '@/lib/templates';
import { voiceById } from '@/lib/voices';
import { apLong } from '@/lib/ap';

// durum sekmeleri: müşterinin dilinde gruplanmış
const TABS: [string, string, OrderStatus[]][] = [['', 'Tümü', []], ['uretim', 'Üretimde', ['PAID', 'QUEUED', 'RENDERING']], ['teslim', 'Teslim', ['DELIVERED']], ['odeme', 'Ödeme bekliyor', ['PENDING_PAYMENT']], ['hata', 'Hata', ['FAILED']]];

export default async function Parsellerim({ searchParams }: { searchParams: Promise<{ q?: string; s?: string }> }) {
  const u = await requireUser();
  const sp = await searchParams; const q = sp.q?.trim().slice(0, 60) || ''; const tab = TABS.find((t) => t[0] === (sp.s || '')) ?? TABS[0];
  const ap = q.match(/^(\d+)\s*[/ ]\s*(\d+)$/); // "101/5" → ada/parsel
  const ci = (x: string) => ({ contains: x, mode: 'insensitive' as const });
  const base: Prisma.OrderWhereInput = { userId: u.id, status: { not: 'CANCELLED' } };
  const search: Prisma.OrderWhereInput = q ? { OR: ap ? [{ ada: ap[1], parsel: ap[2] }] : [{ ada: q }, { mahalle: ci(q) }, { ilce: ci(q) }, { il: ci(q) }, { code: ci(q) }, { headline: ci(q) }] } : {};
  const where: Prisma.OrderWhereInput = { ...base, ...search, ...(tab[2].length ? { status: { in: tab[2] } } : {}) };
  const [orders, total, counts] = await Promise.all([
    prisma.order.findMany({ where, orderBy: { createdAt: 'desc' }, take: 200 }),
    prisma.order.count({ where: base }),
    prisma.order.groupBy({ by: ['status'], where: { ...base, ...search }, _count: true }), // sekme sayıları aramaya göre
  ]);
  const cnt = (st: OrderStatus[]) => counts.filter((c) => !st.length || st.includes(c.status)).reduce((a, c) => a + c._count, 0);
  const code = await ensureRefCode(u);
  const last = orders[0]; const ids = last ? idsOfMahalle(last.mahalleId) : null;
  return (
    <>
      <Head tag={u.company || u.name} title="Parsellerim" action={orders.length > 0 && <Link href="/panel/siparisler" className="text-[13px] font-semibold underline underline-offset-4">Tablo</Link>} />
      {total > 0 && (
        <div className="border-t border-ink/15 px-4 pb-2 pt-3">
          <form className="flex gap-2">
            {sp.s && <input type="hidden" name="s" value={sp.s} />}
            <input name="q" defaultValue={q} placeholder="Ara: 101/5, mahalle, ilçe, kod" className="field h-10 flex-1 text-[14px]" aria-label="Parsellerde ara" />
            <button className="btn-ink btn-sm h-10">Ara</button>
          </form>
          <div className="mt-2 flex gap-1 overflow-x-auto">
            {TABS.map(([k, l, st]) => { const n = cnt(st); const on = tab[0] === k; const h = new URLSearchParams({ ...(k ? { s: k } : {}), ...(q ? { q } : {}) }).toString();
              return <Link key={k} href={`/panel${h ? `?${h}` : ''}`} className={`shrink-0 px-2.5 py-1 text-[12.5px] font-semibold ${on ? 'bg-ink text-white' : 'bg-paper-2 text-ink hover:bg-paper-3'}`}>{l} <span className="num opacity-60">{n}</span></Link>; })}
          </div>
        </div>
      )}
      {total > 0 && orders.length === 0 ? (
        <p className="border-t border-ink/15 px-4 py-6 text-[14px] text-ink-soft">Bu aramaya uyan parsel yok. <Link href="/panel" className="font-semibold text-ink underline underline-offset-2">Tümünü göster</Link></p>
      ) : orders.length === 0 ? (
        <div className="border-t border-ink/15 px-4 py-6">
          <p className="text-[15px] leading-relaxed">Henüz parseliniz yok. İlk ilanınızın ada ve parsel numarasıyla başlayın; sınırı haritada görür, şablonu ve sesi seçip videoyu üretirsiniz.</p>
          <Link href="/panel/yeni" className="btn-signal mt-4 w-full">İlk parseli bul</Link>
          {!u.logoKey && <p className="mt-3 text-[13px] text-ink-soft">Videolarınızın kapanış kartında ofis logonuzun görünmesi için <Link href="/panel/ayarlar" className="font-semibold text-ink underline underline-offset-2">Hesap</Link> sayfasından yükleyin.</p>}
          <p className="mt-3 text-[13px] text-ink-soft">{u.credits > 0 ? `${u.credits} video krediniz var.` : 'Ödemeyi video oluştururken ya da Kredi sekmesinden yaparsınız.'}</p>
        </div>
      ) : (
        <ul className="border-t border-ink/15">
          {orders.map((o) => (
            <li key={o.id}>
              <Link href={`/panel/siparisler/${o.id}`} className="grid grid-cols-[48px_1fr_auto] items-center gap-3 border-b border-ink/10 px-4 py-2.5 hover:bg-paper-2">
                <span className="block h-[84px] w-12 bg-ink">{o.posterKey ? <img src={`/api/orders/${o.id}/download?f=poster`} alt="" loading="lazy" className="h-full w-full object-cover" /> : null}</span>
                <span className="min-w-0">
                  <span className="block truncate text-[15px] font-bold">{apLong(o.ada, o.parsel)}</span>
                  <span className="block truncate text-[13px] text-ink-soft">{o.mahalle}, {o.ilce}{o.areaM2 ? ` · ${Math.round(o.areaM2).toLocaleString('tr-TR')} m²` : ''}</span>
                  <span className="block truncate text-[12.5px] text-ink-soft">{templateById(o.template).name} · {voiceById(o.voice).name}{o.batchId ? ' · toplu' : ''}{o.shareToken ? ' · bağlantı açık' : ''}</span>
                </span>
                <span className="text-right"><StatusBadge s={o.status} />{o.status === 'RENDERING' && <span className="num mt-1 block text-[12px] text-ink-soft">%{o.progress}</span>}</span>
              </Link>
            </li>
          ))}
        </ul>
      )}
      {last && (
        <div className="px-4 py-4">
          <Link href={`/panel/yeni${ids ? `?${new URLSearchParams(ids)}` : ''}`} className="btn-signal w-full">Yeni parsel{ids ? ` · ${last.mahalle}` : ''}</Link>
        </div>
      )}
      <div className="border-t border-ink/15 px-4 py-3 text-[13px] text-ink-soft">Davet kodunuz <b className="text-ink">{code}</b>: davet ettiğiniz kişinin ilk alımında size 1 video kredisi. <Link href="/panel/davet" className="underline underline-offset-2">Ayrıntı</Link></div>
    </>
  );
}
