import Link from 'next/link';
import { ChevronRight, MonitorSmartphone, Plus } from 'lucide-react';
import { prisma } from '@/lib/prisma';
import { requireRole } from '@/lib/auth/dal';
import { getDashboardStats, reportScope, reportsPerDay } from '@/lib/admin/queries';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import type { AuraCalculationResult } from '@/lib/aura/types';
import { parseServices } from '@/lib/reports/services';
import { Button } from '@/components/ui/Button';
import { EmptyState, PageHeader, Panel, ShellPage, StatGrid, type Stat } from '@/components/layout/DashboardPage';
import { OrderStatusPill } from '@/components/account/OrderStatusPill';
import { INTL_LOCALE } from '@/i18n/config';
import { getLocale, getMessages } from '@/i18n/server';
import { PAYMENTS_ENABLED } from '@/lib/features';

export default async function AdminDashboard() {
  const user = await requireRole(['ADMIN', 'SUPER_ADMIN'], '/admin');
  const isSuper = user.role === 'SUPER_ADMIN';
  const locale = await getLocale();
  const all = await getMessages();
  const t = all.dash.admin;
  const c = all.dash.common;
  const intl = INTL_LOCALE[locale];
  const money = (n: number) => all.affiliate.price(n.toLocaleString(intl));
  const dateFmt = new Intl.DateTimeFormat(intl, { day: 'numeric', month: 'short' });
  const timeFmt = new Intl.DateTimeFormat(intl, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
  const meta = chakraMeta(locale);

  const [stats, perDay, recent, sessions, orders] = await Promise.all([
    getDashboardStats(user),
    reportsPerDay(user),
    prisma.report.findMany({
      where: reportScope(user),
      orderBy: { createdAt: 'desc' },
      take: 6,
      select: { id: true, subjectName: true, createdAt: true, services: true, aura: true, event: { select: { name: true } } },
    }),
    prisma.event.findMany({
      where: { status: 'AKTIF', ...(isSuper ? {} : { createdById: user.id }) },
      orderBy: { createdAt: 'desc' },
      take: 5,
      select: { id: true, name: true, location: true, _count: { select: { reports: true } } },
    }),
    isSuper
      ? prisma.order.findMany({
          orderBy: { createdAt: 'desc' },
          take: 5,
          select: { id: true, amount: true, status: true, createdAt: true, user: { select: { name: true } } },
        })
      : Promise.resolve([]),
  ]);

  const statList: Stat[] = [
    { label: t.stats.reports, value: stats.reports.toLocaleString(intl) },
    { label: t.stats.today, value: stats.today },
    { label: t.stats.activeSessions, value: stats.activeSessions },
    ...(isSuper
      ? [
          { label: t.stats.users, value: stats.users.toLocaleString(intl), hint: t.newUsers(stats.newUsers) },
          ...(PAYMENTS_ENABLED
            ? [
                { label: t.stats.revenue, value: money(stats.revenue) },
                { label: t.stats.pendingCommission, value: money(stats.pendingCommission) },
              ]
            : []),
        ]
      : []),
  ];
  const max = Math.max(1, ...perDay.map((d) => d.count));
  const total = perDay.reduce((a, d) => a + d.count, 0);
  const seeAll = (href: string) => (
    <Link href={href} className="text-[13px] font-medium text-accent hover:text-ink">
      {c.seeAll}
    </Link>
  );

  return (
    <ShellPage>
      <PageHeader
        eyebrow={t.eyebrow}
        title={t.title}
        text={t.text}
        actions={
          <>
            {sessions[0] && (
              <Button href={`/admin/sesi/${sessions[0].id}/kios`} variant="outline">
                <MonitorSmartphone className="size-4" aria-hidden />
                {t.kiosk}
              </Button>
            )}
            <Button href="/admin/sesi/baru">
              <Plus className="size-4" aria-hidden />
              {t.newSession}
            </Button>
          </>
        }
      />

      <StatGrid stats={statList} className={isSuper && PAYMENTS_ENABLED ? 'mt-8 lg:grid-cols-3' : 'mt-8'} />

      <Panel title={t.chartTitle} action={<span className="text-[13px] text-muted">{t.chartTotal(total)}</span>} className="mt-6" bodyClassName="p-5">
        <div className="flex h-40 items-end gap-1.5 sm:gap-2">
          {perDay.map((d) => (
            <div key={d.date.toISOString()} className="group flex h-full flex-1 flex-col items-center justify-end gap-1.5">
              <span className="text-[10px] font-medium text-ink opacity-0 tabular-nums transition-opacity group-hover:opacity-100">
                {d.count}
              </span>
              <span
                className="w-full rounded-t-md bg-gradient-to-t from-accent to-accent/60 transition-opacity group-hover:opacity-80"
                style={{ height: `${d.count ? Math.max(4, (d.count / max) * 100) : 2}%`, opacity: d.count ? 1 : 0.25 }}
                title={`${dateFmt.format(d.date)}: ${d.count}`}
              />
            </div>
          ))}
        </div>
        <div className="mt-2 flex justify-between text-[11px] text-subtle">
          <span>{dateFmt.format(perDay[0].date)}</span>
          <span>{dateFmt.format(perDay[perDay.length - 1].date)}</span>
        </div>
      </Panel>

      <div className="mt-6 grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
        <Panel title={t.recentReports} action={seeAll('/admin/laporan')}>
          {recent.length === 0 ? (
            <EmptyState text={t.noReports} />
          ) : (
            <ul className="divide-y divide-line">
              {recent.map((r) => {
                const aura = r.aura as unknown as AuraCalculationResult | null;
                const servicesLabel = parseServices(r.services).map((x) => all.services.short[x]).join(' · ');
                const color = aura ? meta[aura.dominantChakra].color : '#5B6CFF';
                return (
                  <li key={r.id}>
                    <Link href={`/laporan/${r.id}`} className="group flex items-center gap-3 px-5 py-3 transition-colors hover:bg-canvas/60">
                      <span aria-hidden className="size-3 shrink-0 rounded-full" style={{ backgroundColor: color, boxShadow: `0 0 10px ${color}` }} />
                      <span className="min-w-0 flex-1">
                        <span className="block truncate text-sm font-semibold text-ink">{r.subjectName}</span>
                        <span className="block truncate text-xs text-muted">
                          {aura ? meta[aura.dominantChakra].archetype : servicesLabel} · {r.event ? r.event.name : c.personal}
                        </span>
                      </span>
                      <span className="shrink-0 text-xs text-subtle tabular-nums">{timeFmt.format(r.createdAt)}</span>
                    </Link>
                  </li>
                );
              })}
            </ul>
          )}
        </Panel>

        <div className="space-y-6">
          <Panel title={t.activeSessions} action={seeAll('/admin/sesi')}>
            {sessions.length === 0 ? (
              <EmptyState text={t.noActive} />
            ) : (
              <ul className="divide-y divide-line">
                {sessions.map((s) => (
                  <li key={s.id}>
                    <Link href={`/admin/sesi/${s.id}`} className="group flex items-center gap-3 px-5 py-3 transition-colors hover:bg-canvas/60">
                      <span className="size-2 shrink-0 rounded-full bg-wood" aria-hidden />
                      <span className="min-w-0 flex-1">
                        <span className="block truncate text-sm font-semibold text-ink">{s.name}</span>
                        {s.location && <span className="block truncate text-xs text-muted">{s.location}</span>}
                      </span>
                      <span className="text-sm font-semibold text-ink tabular-nums">{s._count.reports}</span>
                      <ChevronRight className="size-4 text-subtle" aria-hidden />
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </Panel>

          {isSuper && PAYMENTS_ENABLED && (
            <Panel title={t.latestOrders} action={seeAll('/admin/transaksi')}>
              {orders.length === 0 ? (
                <EmptyState text={t.noOrders} />
              ) : (
                <ul className="divide-y divide-line">
                  {orders.map((o) => (
                    <li key={o.id} className="flex items-center gap-3 px-5 py-3">
                      <span className="min-w-0 flex-1">
                        <span className="block truncate text-sm font-semibold text-ink">{o.user.name}</span>
                        <span className="block text-xs text-muted tabular-nums">{timeFmt.format(o.createdAt)}</span>
                      </span>
                      <span className="text-right">
                        <span className="block text-sm font-semibold text-ink tabular-nums">{money(o.amount)}</span>
                        <OrderStatusPill status={o.status} label={all.dash.orders.status[o.status]} />
                      </span>
                    </li>
                  ))}
                </ul>
              )}
            </Panel>
          )}
        </div>
      </div>
    </ShellPage>
  );
}
