import Link from 'next/link';
import { notFound } from 'next/navigation';
import { prisma } from '@/lib/db';
import { requireAdminOr404 } from '@/lib/auth';
import { planById } from '@/lib/plans';
import { templateById } from '@/lib/templates';
import { StatusBadge } from '@/components/StatusBadge';
import { AHead, KV, Panel, Stat } from '@/components/admin/ui';
import { ActionForm } from '@/components/admin/ActionForm';
import { ACTION_TR, PAY_TR, dt, n, tryFmt } from '@/lib/admin';
import { adjustCredits, logoutAll, markVerified, sendReset, sendVerify, setRole, setSuspended } from '../../actions';
import { apShort } from '@/lib/ap';

export default async function UserDetail({ params }: { params: Promise<{ id: string }> }) {
  const me = await requireAdminOr404();
  const { id } = await params;
  const u = await prisma.user.findUnique({ where: { id } });
  if (!u) notFound();
  const [orders, byStatus, pays, spent, referrer, invited, logs] = await Promise.all([
    prisma.order.findMany({ where: { userId: id }, orderBy: { createdAt: 'desc' }, take: 50 }),
    prisma.order.groupBy({ by: ['status'], where: { userId: id }, _count: true }),
    prisma.payment.findMany({ where: { userId: id }, orderBy: { createdAt: 'desc' }, take: 50, include: { order: { select: { code: true } } } }),
    prisma.payment.aggregate({ where: { userId: id, status: 'succeeded', plan: { not: 'admin' } }, _sum: { amount: true }, _count: true }),
    u.referredById ? prisma.user.findUnique({ where: { id: u.referredById }, select: { id: true, email: true, name: true, company: true } }) : null,
    prisma.user.findMany({ where: { referredById: id }, orderBy: { createdAt: 'desc' }, take: 50, select: { id: true, email: true, name: true, company: true, createdAt: true, refRewardedAt: true } }),
    prisma.adminLog.findMany({ where: { targetType: 'user', targetId: id }, orderBy: { createdAt: 'desc' }, take: 30 }),
  ]);
  const st = (k: string) => byStatus.find((x) => x.status === k)?._count ?? 0;
  const self = me.id === u.id;
  const h = { id: u.id };
  return (
    <div className="space-y-4">
      <AHead kicker={<Link href="/krtf1krtf/kullanicilar" className="hover:underline">‹ Kullanıcılar</Link>} title={<span className="flex flex-wrap items-center gap-2">{u.company || u.name}
        {u.role === 'ADMIN' && <span className="bg-ink px-1.5 py-0.5 text-[12px] text-white">yönetici</span>}
        {u.disabledAt && <span className="bg-survey px-1.5 py-0.5 text-[12px] text-white">askıda</span>}</span>}>
        <span className="text-[13px] text-ink-soft">{u.email}</span>
      </AHead>

      <div className="grid grid-cols-2 gap-2 md:grid-cols-5">
        <Stat k="Kredi" v={u.credits} />
        <Stat k="Harcama" v={tryFmt(spent._sum.amount ?? 0)} sub={`${n(spent._count)} ödeme`} />
        <Stat k="Sipariş" v={n(orders.length)} sub={`${st('DELIVERED')} teslim · ${st('FAILED')} hata`} />
        <Stat k="Ödeme bekleyen sipariş" v={n(st('PENDING_PAYMENT'))} tone={st('PENDING_PAYMENT') ? 'warn' : undefined} />
        <Stat k="Davet ettiği" v={n(invited.length)} sub={`${invited.filter((x) => x.refRewardedAt).length} ödeme yaptı`} />
      </div>

      <div className="grid gap-4 xl:grid-cols-[1fr_340px]">
        <div className="space-y-4">
          <Panel title="Profil">
            <KV rows={[
              ['Ad', u.name], ['Firma', u.company], ['E-posta', u.email], ['Telefon', u.phone],
              ['E-posta doğrulama', u.emailVerifiedAt ? dt(u.emailVerifiedAt) : <span className="text-survey-dark">doğrulanmadı</span>],
              ['Kayıt', dt(u.createdAt)], ['Davet kodu', u.refCode], ['Davet eden', referrer ? <Link href={`/krtf1krtf/kullanicilar/${referrer.id}`} className="underline">{referrer.company || referrer.name} · {referrer.email}</Link> : null],
              ['Davet ödülü', u.refRewardedAt ? `verildi · ${dt(u.refRewardedAt)}` : null], ['Logo', u.logoKey ? 'yüklü' : 'yok'],
              ['Askı', u.disabledAt ? dt(u.disabledAt) : null], ['Kimlik', <span key="id" className="font-mono text-[12px]">{u.id}</span>],
            ]} />
          </Panel>

          <Panel title={`Siparişler (${orders.length}${orders.length === 50 ? '+' : ''})`} action={<Link href={`/krtf1krtf/siparisler?q=${encodeURIComponent(u.email)}`} className="text-[12px] underline">Filtreli listede aç</Link>} pad={false}>
            {orders.length ? (
              <table className="w-full text-left text-[13px]"><tbody>{orders.map((o) => (
                <tr key={o.id} className="border-b border-ink/5 hover:bg-paper-2 [&>td]:px-4 [&>td]:py-2">
                  <td><Link href={`/krtf1krtf/siparisler/${o.id}`} className="font-mono font-bold hover:underline">{o.code}</Link></td>
                  <td>{apShort(o.ada, o.parsel)} · {o.mahalle}</td><td>{templateById(o.template).name}</td><td><StatusBadge s={o.status} /></td><td className="num text-[12px]">{dt(o.createdAt)}</td>
                </tr>))}</tbody></table>
            ) : <p className="px-4 py-3 text-[13px] text-ink-soft">Sipariş yok.</p>}
          </Panel>

          <Panel title="Ödemeler ve kredi hareketleri" pad={false}>
            {pays.length ? (
              <table className="w-full text-left text-[13px]"><tbody>{pays.map((p) => (
                <tr key={p.id} className="border-b border-ink/5 [&>td]:px-4 [&>td]:py-2">
                  <td className="num text-[12px]">{dt(p.createdAt)}</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">{p.credits > 0 ? '+' : ''}{p.credits} kredi</td><td className="num">{tryFmt(p.amount, p.currency)}</td><td>{PAY_TR[p.status] || p.status}</td>
                  <td>{p.order ? <span className="font-mono text-[12px]">{p.order.code}</span> : null}</td>
                </tr>))}</tbody></table>
            ) : <p className="px-4 py-3 text-[13px] text-ink-soft">Ödeme yok.</p>}
          </Panel>

          {invited.length > 0 && (
            <Panel title="Davet ettiği kişiler" pad={false}>
              <ul className="divide-y divide-ink/5">{invited.map((x) => <li key={x.id}><Link href={`/krtf1krtf/kullanicilar/${x.id}`} className="block px-4 py-2 text-[13px] hover:bg-paper-2"><b>{x.company || x.name}</b> · {x.email} <span className="text-ink-soft">· {dt(x.createdAt)}{x.refRewardedAt ? ' · ödül verildi' : ''}</span></Link></li>)}</ul>
            </Panel>
          )}

          {logs.length > 0 && (
            <Panel title="Yönetici işlemleri" pad={false}>
              <ul className="divide-y divide-ink/5">{logs.map((l) => <li key={l.id} className="px-4 py-2 text-[13px]"><b>{ACTION_TR[l.action] || l.action}</b> · {l.adminEmail} <span className="text-ink-soft">· {dt(l.createdAt)}</span>{l.detail ? <span className="block font-mono text-[11.5px] text-ink-soft">{JSON.stringify(l.detail)}</span> : null}</li>)}</ul>
            </Panel>
          )}
        </div>

        <div className="space-y-4">
          <Panel title="Kredi düzenle">
            <ActionForm action={adjustCredits} hidden={h} label="Krediyi işle" tone="ink" confirm="Kredi değişikliği işlenecek ve günlüğe yazılacak. Devam edilsin mi?" fields={
              <div className="mb-2 grid grid-cols-[90px_1fr] gap-2">
                <label><span className="label">Adet (±)</span><input name="delta" type="number" min={-500} max={500} defaultValue={1} required className="field h-9 text-[14px]" /></label>
                <label><span className="label">Not</span><input name="note" required minLength={2} maxLength={120} placeholder="örn. hatalı render telafisi" className="field h-9 text-[14px]" /></label>
              </div>} />
            <p className="mt-2 text-[12px] text-ink-soft">Eksi değer kredi düşer. Ödeme geçmişine 0 TL’lik “yönetici tanımı” olarak yazılır.</p>
          </Panel>
          <Panel title="Hesap">
            <div className="space-y-2">
              {!u.emailVerifiedAt && <ActionForm action={markVerified} hidden={h} label="E-postayı doğrulanmış işaretle" />}
              {!u.emailVerifiedAt && <ActionForm action={sendVerify} hidden={h} label="Doğrulama e-postası gönder" />}
              <ActionForm action={sendReset} hidden={h} label="Şifre sıfırlama e-postası gönder" confirm={`${u.email} adresine şifre sıfırlama bağlantısı gönderilecek.`} />
              {!self && <ActionForm action={logoutAll} hidden={h} label="Tüm oturumları kapat" confirm="Kullanıcı tüm cihazlarda çıkış yapmış olacak." />}
              {!self && <ActionForm action={setRole} hidden={{ ...h, role: u.role === 'ADMIN' ? 'USER' : 'ADMIN' }} label={u.role === 'ADMIN' ? 'Yöneticilikten çıkar' : 'Yönetici yap'} confirm={u.role === 'ADMIN' ? 'Yönetici yetkisi kaldırılacak.' : 'Bu kullanıcı tüm yönetim paneline erişebilecek. Emin misiniz?'} />}
              {!self && (u.disabledAt
                ? <ActionForm action={setSuspended} hidden={{ ...h, on: '0' }} label="Askıyı kaldır" tone="ink" />
                : <ActionForm action={setSuspended} hidden={{ ...h, on: '1' }} label="Hesabı askıya al" tone="danger" confirm="Kullanıcı giriş yapamayacak ve tüm oturumları kapanacak. Emin misiniz?"
                  fields={<input name="reason" maxLength={120} placeholder="Neden (günlüğe yazılır)" className="field mb-2 h-9 text-[14px]" />} />)}
              {self && <p className="text-[12px] text-ink-soft">Kendi hesabınızda rol, askı ve oturum işlemleri kapalıdır.</p>}
            </div>
          </Panel>
        </div>
      </div>
    </div>
  );
}
