import Link from 'next/link';
import { Search } from 'lucide-react';
import type { Prisma } from '@prisma/client';
import { prisma } from '@/lib/prisma';
import { requireRole } from '@/lib/auth/dal';
import { reportScope } from '@/lib/admin/queries';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import type { AuraCalculationResult } from '@/lib/aura/types';
import { parseServices } from '@/lib/reports/services';
import { EmptyState, PageHeader, Pager, Panel, ShellPage } from '@/components/layout/DashboardPage';
import { INTL_LOCALE } from '@/i18n/config';
import { getLocale, getMessages } from '@/i18n/server';
import { cn } from '@/lib/cn';

const PAGE_SIZE = 30;
const SOURCES = ['sesi', 'pribadi'] as const;
type Source = (typeof SOURCES)[number];

export default async function AdminReportsPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const user = await requireRole(['ADMIN', 'SUPER_ADMIN'], '/admin/laporan');
  const locale = await getLocale();
  const all = await getMessages();
  const t = all.dash.adminReports;
  const c = all.dash.common;
  const meta = chakraMeta(locale);
  const timeFmt = new Intl.DateTimeFormat(INTL_LOCALE[locale], { day: 'numeric', month: 'short', year: 'numeric' });

  const sp = await searchParams;
  const q = typeof sp.q === 'string' ? sp.q.trim().slice(0, 80) : '';
  const source = SOURCES.includes(sp.sumber as Source) ? (sp.sumber as Source) : undefined;
  const page = Math.max(1, Number(sp.hal) || 1);

  const where: Prisma.ReportWhereInput = {
    AND: [
      reportScope(user),
      q ? { OR: [{ subjectName: { contains: q } }, { subjectEmail: { contains: q } }] } : {},
      source === 'sesi' ? { eventId: { not: null } } : source === 'pribadi' ? { eventId: null } : {},
    ],
  };
  const [total, rows] = await Promise.all([
    prisma.report.count({ where }),
    prisma.report.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
      select: {
        id: true,
        subjectName: true,
        createdAt: true,
        services: true,
        aura: true,
        ownerId: true,
        owner: { select: { name: true } },
        event: { select: { id: true, name: true } },
      },
    }),
  ]);
  const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  const href = (opts: { sumber?: Source; hal?: number }) => {
    const p = new URLSearchParams();
    if (q) p.set('q', q);
    const s = 'sumber' in opts ? opts.sumber : source;
    if (s) p.set('sumber', s);
    if (opts.hal && opts.hal > 1) p.set('hal', String(opts.hal));
    const str = p.toString();
    return str ? `/admin/laporan?${str}` : '/admin/laporan';
  };

  return (
    <ShellPage>
      <PageHeader eyebrow={t.eyebrow} title={t.title} text={t.text} />

      <div className="mt-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <nav className="no-scrollbar -mx-1 flex gap-1 overflow-x-auto">
          {[undefined, ...SOURCES].map((s) => (
            <a
              key={s ?? 'all'}
              href={href({ sumber: s })}
              aria-current={source === s ? 'page' : undefined}
              className={cn(
                'rounded-full px-3.5 py-1.5 text-[13px] font-medium whitespace-nowrap transition-colors',
                source === s ? 'bg-ink text-white' : 'text-muted hover:text-ink',
              )}
            >
              {s === 'sesi' ? c.session : s === 'pribadi' ? c.personal : c.all}
            </a>
          ))}
        </nav>
        <form role="search" className="relative sm:w-72">
          {source && <input type="hidden" name="sumber" value={source} />}
          <Search className="pointer-events-none absolute top-1/2 left-4 size-4 -translate-y-1/2 text-subtle" aria-hidden />
          <label htmlFor="q" className="sr-only">
            {c.search}
          </label>
          <input
            id="q"
            name="q"
            type="search"
            defaultValue={q}
            placeholder={t.searchPlaceholder}
            className="h-10 w-full rounded-full bg-surface pr-4 pl-10 text-[13px] text-ink ring-1 ring-line placeholder:text-subtle focus:ring-2 focus:ring-ink/70 focus:outline-none"
          />
        </form>
      </div>

      <Panel className="mt-6">
        {rows.length === 0 ? (
          <EmptyState text={t.empty} />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[720px] text-left text-sm">
              <thead className="border-b border-line text-[12px] text-subtle">
                <tr>
                  {[t.cols.name, t.cols.profile, t.cols.source, t.cols.owner, t.cols.date].map((h) => (
                    <th key={h} scope="col" className="px-5 py-3 font-medium">
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-line">
                {rows.map((r) => {
                  const aura = r.aura as unknown as AuraCalculationResult | null;
                const servicesLabel = parseServices(r.services).map((x) => all.services.short[x]).join(' · ');
                  const m = aura ? meta[aura.dominantChakra] : undefined;
                  return (
                    <tr key={r.id} className="transition-colors hover:bg-canvas/60">
                      <td className="px-5 py-3.5">
                        <Link href={`/laporan/${r.id}`} className="font-semibold text-ink hover:underline">
                          {r.subjectName}
                        </Link>
                      </td>
                      <td className="px-5 py-3.5">
                        <span className="flex items-center gap-2 text-ink-soft">
                          <span aria-hidden className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: m?.color ?? '#5B6CFF' }} />
                          {m?.archetype ?? servicesLabel}
                        </span>
                      </td>
                      <td className="px-5 py-3.5 text-muted">
                        {r.event ? (
                          <Link href={`/admin/sesi/${r.event.id}`} className="hover:text-ink hover:underline">
                            {r.event.name}
                          </Link>
                        ) : (
                          c.personal
                        )}
                      </td>
                      <td className="px-5 py-3.5">
                        {r.owner ? <span className="text-ink-soft">{r.owner.name}</span> : <span className="text-subtle">{t.unclaimed}</span>}
                      </td>
                      <td className="px-5 py-3.5 text-muted tabular-nums">{timeFmt.format(r.createdAt)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </Panel>
      <Pager page={page} pages={pages} href={(n) => href({ hal: n })} labels={c} />
    </ShellPage>
  );
}
