import type { Metadata } from 'next';
import Link from 'next/link';
import { ArrowRight, Camera, FileText, Gift, UserRound, type LucideIcon } from 'lucide-react';
import { prisma } from '@/lib/prisma';
import { requireUser } from '@/lib/auth/dal';
import { listOwnReports } from '@/lib/reports/access';
import { hasPurchased } from '@/lib/affiliate';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import type { ChakraType } from '@/lib/aura/types';
import { NewScanButton } from '@/components/account/NewScanButton';
import { ReportCard } from '@/components/account/ReportCard';
import { EmptyState, PageHeader, Panel, ShellPage, StatGrid } from '@/components/layout/DashboardPage';
import { INTL_LOCALE } from '@/i18n/config';
import { getLocale, getMessages } from '@/i18n/server';
import { PAYMENTS_ENABLED } from '@/lib/features';

export async function generateMetadata(): Promise<Metadata> {
  return { title: (await getMessages()).account.meta };
}

export default async function AccountOverview({ searchParams }: PageProps<'/akun'>) {
  const user = await requireUser('/akun');
  const autoScan = (await searchParams).foto === '1';
  const locale = await getLocale();
  const all = await getMessages();
  const t = all.dash.overview;
  const intl = INTL_LOCALE[locale];
  const money = (n: number) => all.affiliate.price(n.toLocaleString(intl));

  const [reports, premium, pending] = await Promise.all([
    listOwnReports(user.id),
    hasPurchased(user.id),
    prisma.commission.aggregate({ where: { status: 'PENDING', affiliate: { userId: user.id } }, _sum: { amount: true } }),
  ]);
  const latest = reports[0];
  const usedServices = new Set(reports.flatMap((r) => r.services)).size;
  const latestMeta = latest?.dominantChakra ? chakraMeta(locale)[latest.dominantChakra as ChakraType] : null;
  const latestTitle = latestMeta?.archetype ?? latest?.services.map((sv) => all.services.names[sv]).join(' · ');
  const color = latestMeta?.color ?? '#5B6CFF';

  const quick: { href: string; icon: LucideIcon; text: string[] }[] = [
    { href: '/akun?foto=1', icon: Camera, text: t.quick.scan },
    { href: '/akun/laporan', icon: FileText, text: t.quick.reports },
    ...(PAYMENTS_ENABLED ? [{ href: '/akun/afiliasi', icon: Gift, text: t.quick.share }] : []),
    { href: '/akun/profil', icon: UserRound, text: t.quick.profile },
  ];

  return (
    <ShellPage>
      <PageHeader
        eyebrow={t.eyebrow}
        title={t.hello(user.name.split(' ')[0])}
        text={t.text}
        actions={<NewScanButton key={autoScan ? "auto" : "button"} autoOpen={autoScan} userName={user.name} />}
      />

      <StatGrid
        className="mt-8"
        stats={[
          { label: t.stats.reports, value: reports.length },
          { label: t.stats.aura, value: latestMeta?.short ?? '—' },
          ...(PAYMENTS_ENABLED
            ? [
                { label: t.stats.premium, value: premium ? t.premiumYes : t.premiumNo },
                { label: t.stats.earnings, value: money(pending._sum.amount ?? 0) },
              ]
            : [{ label: all.services.usedLabel, value: `${usedServices}/3` }]),
        ]}
      />

      <div className="mt-6 grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
        {latest ? (
          <Link
            href={`/laporan/${latest.id}`}
            className="group relative flex min-h-[260px] flex-col justify-end overflow-hidden rounded-panel bg-night-950 p-6 text-white sm:p-8"
          >
            {latest.photo && (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={latest.photo} alt="" className="absolute inset-0 size-full object-cover opacity-45 transition-transform duration-700 group-hover:scale-105" />
            )}
            <div
              aria-hidden
              className="absolute inset-0"
              style={{ background: `linear-gradient(to top, #070B19 15%, ${color}55 70%, transparent)` }}
            />
            <div className="relative">
              <p className="eyebrow text-white/60">{t.latestTitle}</p>
              <h2 className="mt-3 text-[28px] leading-tight font-semibold tracking-[-0.02em]">{latestTitle}</h2>
              <p className="mt-1 text-sm text-white/65">
                {latestMeta ? `${latestMeta.name} · ` : ''}
                {new Intl.DateTimeFormat(intl, { day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(latest.createdAt))}
              </p>
              <span className="mt-5 inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-[13px] font-semibold text-ink">
                {t.openReport}
                <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" aria-hidden />
              </span>
            </div>
          </Link>
        ) : (
          <Panel>
            <EmptyState title={t.noReportTitle} text={t.noReportText}>
              <NewScanButton userName={user.name} />
            </EmptyState>
          </Panel>
        )}

        <Panel title={t.quickTitle} bodyClassName="grid grid-cols-2 gap-px bg-line [&>*:last-child:nth-child(odd)]:col-span-2">
          {quick.map(({ href, icon: Icon, text: [title, text] }) => (
            <Link key={href} href={href} className="group bg-surface p-4 transition-colors hover:bg-canvas">
              <span className="inline-flex size-9 items-center justify-center rounded-full bg-accent-soft text-accent">
                <Icon className="size-4" aria-hidden />
              </span>
              <span className="mt-3 block text-sm font-semibold text-ink">{title}</span>
              <span className="mt-0.5 block text-xs leading-relaxed text-muted">{text}</span>
            </Link>
          ))}
        </Panel>
      </div>

      {reports.length > 1 && (
        <section className="mt-10">
          <div className="flex items-center justify-between">
            <h2 className="text-[15px] font-semibold text-ink">{t.recentTitle}</h2>
            <Link href="/akun/laporan" className="text-[13px] font-medium text-accent hover:text-ink">
              {all.dash.common.seeAll}
            </Link>
          </div>
          <ul className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {reports.slice(1, 4).map((r) => (
              <ReportCard key={r.id} report={r} locale={locale} sessionLabel={all.dash.reports.fromSession} serviceNames={all.services.short} />
            ))}
          </ul>
        </section>
      )}
    </ShellPage>
  );
}
