import type { Metadata } from 'next';
import { redirect } from 'next/navigation';
import { PAYMENTS_ENABLED } from '@/lib/features';
import { headers } from 'next/headers';
import { CheckCircle2, Clock, XCircle } from 'lucide-react';
import { prisma } from '@/lib/prisma';
import { requireUser } from '@/lib/auth/dal';
import { syncOrder, savePayoutAccount } from '@/app/actions/affiliate';
import { AFFILIATE_RATE_PERCENT, PREMIUM_PRICE } from '@/lib/payments/midtrans';
import { readAuraField } from '@/lib/aura/auraField';
import { pickAuraType } from '@/lib/aura/auraReport';
import type { AuraCalculationResult } from '@/lib/aura/types';
import { PageHeader, ShellPage } from '@/components/layout/DashboardPage';
import { Button } from '@/components/ui/Button';
import { SubmitButton } from '@/components/ui/Field';
import { BuyPremiumButton, CopyField, ShareCard } from '@/components/affiliate/AffiliateClient';
import { INTL_LOCALE } from '@/i18n/config';
import { getLocale, getMessages } from '@/i18n/server';

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

export default async function AffiliatePage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const user = await requireUser('/akun/afiliasi');
  if (!PAYMENTS_ENABLED) redirect('/akun');
  const locale = await getLocale();
  const all = await getMessages();
  const t = all.affiliate;
  const money = (n: number) => t.price(n.toLocaleString(INTL_LOCALE[locale]));
  const dateFmt = new Intl.DateTimeFormat(INTL_LOCALE[locale], { day: 'numeric', month: 'short', year: 'numeric' });

  // Returning from Midtrans: confirm the payment before rendering.
  const orderRef = (await searchParams).order;
  const order = typeof orderRef === 'string' ? await syncOrder(orderRef) : null;

  const affiliate = await prisma.affiliate.findUnique({
    where: { userId: user.id },
    include: {
      commissions: { orderBy: { createdAt: 'desc' }, take: 50, include: { order: { select: { user: { select: { name: true } } } } } },
    },
  });

  const h = await headers();
  const origin =
    process.env.NEXT_PUBLIC_APP_URL?.replace(/\/$/, '') || `${h.get('x-forwarded-proto') ?? 'http'}://${h.get('host')}`;
  const link = affiliate ? `${origin}/?ref=${affiliate.code}` : '';

  const latest = affiliate
    ? await prisma.report.findFirst({
        where: { ownerId: user.id, photo: { not: null } },
        orderBy: { createdAt: 'desc' },
        select: { photo: true, aura: true },
      })
    : null;
  const aura = latest?.aura as unknown as AuraCalculationResult | undefined;
  const zones = aura
    ? readAuraField(aura.normalizedScores, { dominant: aura.dominantChakra, secondary: aura.secondaryChakra }, locale)
    : null;
  const type = aura ? pickAuraType(aura, locale) : null;

  const sum = (status: 'PENDING' | 'PAID') =>
    affiliate?.commissions.filter((c) => c.status === status).reduce((a, c) => a + c.amount, 0) ?? 0;

  const banner =
    order?.status === 'PAID'
      ? { icon: CheckCircle2, tone: 'bg-wood/10 text-wood', title: t.status.paidTitle, text: t.status.paidText }
      : order?.status === 'PENDING'
        ? { icon: Clock, tone: 'bg-earth/10 text-earth', title: t.status.pendingTitle, text: t.status.pendingText }
        : order
          ? { icon: XCircle, tone: 'bg-fire/10 text-fire', title: t.status.failedTitle, text: t.status.failedText }
          : null;

  return (
    <ShellPage className="max-w-[960px]">
        {banner && (
          <div className={`mb-8 flex gap-3 rounded-card p-5 ${banner.tone}`}>
            <banner.icon className="mt-0.5 size-5 shrink-0" aria-hidden />
            <div>
              <p className="text-sm font-semibold">{banner.title}</p>
              <p className="mt-1 text-[13px] leading-relaxed text-ink-soft">{banner.text}</p>
            </div>
          </div>
        )}

        <PageHeader eyebrow={t.dashboard.eyebrow} title={t.dashboard.title} text={t.dashboard.text(AFFILIATE_RATE_PERCENT)} />

        {!affiliate ? (
          <div className="mt-10 rounded-panel bg-surface p-8 shadow-card ring-1 ring-line/70">
            <p className="text-lg font-semibold text-ink">{t.upsell.title}</p>
            <p className="mt-2 max-w-lg text-sm leading-relaxed text-muted">{t.upsell.text(AFFILIATE_RATE_PERCENT)}</p>
            <p className="mt-6 text-2xl font-semibold text-ink">{money(PREMIUM_PRICE)}</p>
            <BuyPremiumButton className="mt-4" />
            <p className="mt-4 text-xs text-subtle">{t.dashboard.notYet}</p>
          </div>
        ) : (
          <div className="mt-10 space-y-6">
            <div className="grid gap-4 rounded-panel bg-surface p-6 shadow-card ring-1 ring-line/70 sm:grid-cols-2 sm:p-8">
              <CopyField label={t.dashboard.code} value={affiliate.code} />
              <CopyField label={t.dashboard.link} value={link} />
            </div>

            <dl className="grid grid-cols-3 gap-px overflow-hidden rounded-card bg-line shadow-card ring-1 ring-line">
              {[
                [t.dashboard.stats.referrals, String(affiliate.commissions.filter((c) => c.status !== 'CANCELLED').length)],
                [t.dashboard.stats.pending, money(sum('PENDING'))],
                [t.dashboard.stats.paid, money(sum('PAID'))],
              ].map(([label, value]) => (
                <div key={label} className="bg-surface p-5">
                  <dt className="text-[13px] text-muted">{label}</dt>
                  <dd className="mt-2 text-xl font-semibold tracking-tight text-ink tabular-nums">{value}</dd>
                </div>
              ))}
            </dl>

            <section className="rounded-panel bg-surface p-6 shadow-card ring-1 ring-line/70 sm:p-8">
              <h2 className="text-[15px] font-semibold text-ink">{t.dashboard.shareTitle}</h2>
              <p className="mt-1 text-sm text-muted">{t.dashboard.shareText}</p>
              <div className="mt-6">
                {latest?.photo && zones && type ? (
                  <ShareCard
                    photo={latest.photo}
                    zones={zones}
                    typeName={type.name}
                    typeColor={type.color}
                    code={affiliate.code}
                    link={link}
                  />
                ) : (
                  <div className="flex flex-col items-start gap-4">
                    <p className="text-sm text-ink-soft">{t.dashboard.noPhoto}</p>
                    <Button href="/akun?foto=1">{t.dashboard.takePhoto}</Button>
                  </div>
                )}
              </div>
            </section>

            <section className="rounded-panel bg-surface p-6 shadow-card ring-1 ring-line/70 sm:p-8">
              <h2 className="text-[15px] font-semibold text-ink">{t.dashboard.payoutTitle}</h2>
              <p className="mt-1 text-sm text-muted">{t.dashboard.payoutText}</p>
              <form action={savePayoutAccount} className="mt-4 flex flex-col gap-3 sm:flex-row">
                <input
                  name="payoutAccount"
                  defaultValue={affiliate.payoutAccount ?? ''}
                  placeholder={t.dashboard.payoutPlaceholder}
                  maxLength={200}
                  className="h-12 flex-1 rounded-2xl bg-surface px-4 text-[15px] text-ink ring-1 ring-line placeholder:text-subtle focus:ring-2 focus:ring-ink/80 focus:outline-none"
                />
                <SubmitButton className="sm:w-auto">{t.dashboard.save}</SubmitButton>
              </form>
            </section>

            <section className="rounded-panel bg-surface p-6 shadow-card ring-1 ring-line/70 sm:p-8">
              <h2 className="text-[15px] font-semibold text-ink">{t.dashboard.historyTitle}</h2>
              {affiliate.commissions.length === 0 ? (
                <p className="mt-3 text-sm text-muted">{t.dashboard.historyEmpty}</p>
              ) : (
                <ul className="mt-4 divide-y divide-line">
                  {affiliate.commissions.map((c) => (
                    <li key={c.id} className="flex items-center justify-between gap-4 py-3 text-sm">
                      <span className="min-w-0">
                        <span className="block truncate font-medium text-ink">{c.order.user.name}</span>
                        <span className="text-xs text-subtle">{dateFmt.format(c.createdAt)}</span>
                      </span>
                      <span className="text-right">
                        <span className="block font-semibold text-ink tabular-nums">{money(c.amount)}</span>
                        <span className={`text-xs ${c.status === 'PAID' ? 'text-wood' : 'text-subtle'}`}>
                          {t.dashboard.statusLabel[c.status]}
                        </span>
                      </span>
                    </li>
                  ))}
                </ul>
              )}
            </section>
          </div>
        )}
    </ShellPage>
  );
}
