import Link from 'next/link';
import { prisma } from '@/lib/db';
import { AHead, Filters, Pager, fieldSm } from '@/components/admin/ui';
import { ACTION_TR, PAGE, dt, href, page } from '@/lib/admin';

const TARGET: Record<string, string> = { order: '/krtf1krtf/siparisler/', user: '/krtf1krtf/kullanicilar/' };

export default async function AuditLog({ searchParams }: { searchParams: Promise<{ a?: string; who?: string; page?: string }> }) {
  const sp = await searchParams; const pg = page(sp.page);
  const where = { ...(sp.a ? { action: sp.a } : {}), ...(sp.who ? { adminEmail: { contains: sp.who, mode: 'insensitive' as const } } : {}) };
  const [rows, total] = await Promise.all([
    prisma.adminLog.findMany({ where, orderBy: { createdAt: 'desc' }, skip: (pg - 1) * PAGE, take: PAGE }),
    prisma.adminLog.count({ where }),
  ]);
  const params = sp as Record<string, string | undefined>;
  return (
    <div className="space-y-3">
      <AHead kicker="Yönetim" title="İşlem günlüğü" />
      <p className="text-[13px] text-ink-soft">Yönetim panelinden yapılan her değişiklik burada: kim, ne zaman, neye ve ne yaptı. Kayıtlar silinemez.</p>
      <Filters reset="/krtf1krtf/gunluk">
        <label className="flex flex-col"><span className="label">İşlem</span><select name="a" defaultValue={sp.a || ''} className={fieldSm}><option value="">Tümü</option>{Object.entries(ACTION_TR).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></label>
        <label className="flex flex-col"><span className="label">Yönetici</span><input name="who" defaultValue={sp.who} placeholder="e-posta" className={`${fieldSm} w-56`} /></label>
      </Filters>
      <div className="overflow-x-auto bg-white">
        <table className="w-full min-w-[760px] text-left text-[13px]">
          <thead className="border-b border-ink/15"><tr className="[&>th]:tag [&>th]:px-3 [&>th]:py-2"><th>Zaman</th><th>Yönetici</th><th>İşlem</th><th>Hedef</th><th>Ayrıntı</th></tr></thead>
          <tbody>
            {rows.map((l) => (
              <tr key={l.id} className="border-b border-ink/5 align-top [&>td]:px-3 [&>td]:py-2">
                <td className="num whitespace-nowrap text-[12px]">{dt(l.createdAt)}</td>
                <td className="text-[12.5px]">{l.adminEmail}</td>
                <td className="font-semibold">{ACTION_TR[l.action] || l.action}</td>
                <td>{l.targetId && TARGET[l.targetType] ? <Link href={TARGET[l.targetType] + l.targetId} className="font-mono text-[12px] underline">{l.targetType}</Link> : <span className="font-mono text-[12px]">{l.targetType}</span>}</td>
                <td className="max-w-[360px] break-words font-mono text-[11.5px] text-ink-soft">{l.detail ? JSON.stringify(l.detail) : ''}</td>
              </tr>
            ))}
            {!rows.length && <tr><td colSpan={5} className="px-3 py-6 text-center text-ink-soft">Henüz kayıt yok.</td></tr>}
          </tbody>
        </table>
      </div>
      <Pager page={pg} total={total} size={PAGE} link={(p) => href('/krtf1krtf/gunluk', params, { page: p })} />
    </div>
  );
}
