import Link from 'next/link';
import { ChevronRight, Plus } from 'lucide-react';
import { requireRole } from '@/lib/auth/dal';
import { getEventStats, listEvents } from '@/lib/events/queries';
import { Button } from '@/components/ui/Button';
import { ShellPage } from '@/components/layout/DashboardPage';
import { StatusPill } from '@/components/admin/StatusPill';
import { getLocale, getMessages } from '@/i18n/server';
import { INTL_LOCALE } from '@/i18n/config';

export default async function SessionsPage() {
  const user = await requireRole(['ADMIN', 'SUPER_ADMIN'], '/admin/sesi');
  const [stats, events] = await Promise.all([getEventStats(user), listEvents(user)]);
  const isSuper = user.role === 'SUPER_ADMIN';
  const all = (await getMessages()).admin;
  const t = all.home;
  const dateFmt = new Intl.DateTimeFormat(INTL_LOCALE[await getLocale()], { day: 'numeric', month: 'short', year: 'numeric' });

  return (
    <ShellPage>
      <div className="flex flex-col gap-6 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p className="eyebrow text-subtle">{t.eyebrow}</p>
          <h1 className="mt-4 text-[32px] leading-tight font-semibold tracking-[-0.02em] text-ink">{t.title}</h1>
          <p className="mt-2 max-w-lg text-[15px] text-muted">
            {t.text}
          </p>
        </div>
        <Button href="/admin/sesi/baru">
          <Plus className="size-4" aria-hidden />
          {t.newSession}
        </Button>
      </div>

      <dl className="mt-10 grid grid-cols-3 gap-px overflow-hidden rounded-card bg-line shadow-card ring-1 ring-line">
        {[
          [t.activeSessions, stats.activeEvents],
          [t.totalParticipants, stats.participants],
          [t.today, stats.today],
        ].map(([label, value]) => (
          <div key={label} className="bg-surface p-5 sm:p-6">
            <dt className="text-[13px] text-muted">{label}</dt>
            <dd className="mt-2 text-[28px] font-semibold tracking-tight text-ink tabular-nums">{value}</dd>
          </div>
        ))}
      </dl>

      <section aria-labelledby="sessions" className="mt-12">
        <h2 id="sessions" className="text-[15px] font-semibold text-ink">
          {isSuper ? t.allSessions : t.mySessions}
        </h2>

        {events.length === 0 ? (
          <div className="mt-4 rounded-panel bg-surface px-6 py-16 text-center shadow-card ring-1 ring-line/70">
            <p className="text-lg font-semibold text-ink">{t.emptyTitle}</p>
            <p className="mx-auto mt-2 max-w-sm text-sm leading-relaxed text-muted">
              {t.emptyText}
            </p>
            <Button href="/admin/sesi/baru" variant="outline" className="mt-6">
              {t.firstSession}
            </Button>
          </div>
        ) : (
          <ul className="mt-4 divide-y divide-line overflow-hidden rounded-card bg-surface shadow-card ring-1 ring-line/70">
            {events.map((e) => (
              <li key={e.id}>
                <Link
                  href={`/admin/sesi/${e.id}`}
                  className="group flex items-center gap-4 px-5 py-4 transition-colors hover:bg-canvas/60"
                >
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="truncate text-[15px] font-semibold text-ink">{e.name}</span>
                      <StatusPill status={e.status} label={all.status[e.status]} />
                    </div>
                    <p className="mt-1 truncate text-[13px] text-muted">
                      {[all.kinds[e.kind], e.location, e.date && dateFmt.format(e.date), isSuper && t.by(e.createdBy.name)]
                        .filter(Boolean)
                        .join(' · ')}
                    </p>
                  </div>
                  <span className="text-right">
                    <span className="block text-[17px] font-semibold text-ink tabular-nums">{e._count.reports}</span>
                    <span className="block text-[11px] text-subtle">{t.participants}</span>
                  </span>
                  <ChevronRight className="size-4 text-subtle transition-transform group-hover:translate-x-0.5" aria-hidden />
                </Link>
              </li>
            ))}
          </ul>
        )}
      </section>
    </ShellPage>
  );
}
