import Link from 'next/link'
import { redirect } from 'next/navigation'

import { LoginForm, type DemoAccount } from '@/components/site/login-form'
import { LanguageSwitcher } from '@/components/site/language-switcher'
import { Wordmark } from '@/components/brand/logo'
import { DemoDataBadge, Panel } from '@/components/ui/display'
import { getCurrentUser, homePathFor } from '@/lib/auth/current-user'
import { env } from '@/lib/env'
import { getI18n } from '@/lib/i18n/server'
import { prisma } from '@/lib/db'

export const dynamic = 'force-dynamic'

export default async function LoginPage({
  searchParams,
}: {
  searchParams: Promise<{ next?: string }>
}) {
  const { t, locale } = await getI18n()
  const user = await getCurrentUser()
  if (user) redirect(homePathFor(user))

  const params = await searchParams

  // The demo roster is only assembled when the environment explicitly enables it.
  const demoAccounts: DemoAccount[] = env.demoAccountsEnabled
    ? (
        await prisma.user.findMany({
          where: { isActive: true },
          select: {
            email: true,
            name: true,
            nameAr: true,
            roles: { select: { role: { select: { key: true, level: true } } } },
          },
          take: 8,
        })
      )
        .map((account) => ({
          account,
          level: account.roles[0]?.role.level ?? 0,
        }))
        .sort((a, b) => b.level - a.level)
        .map(({ account }) => ({
          email: account.email,
          name: account.name,
          nameAr: account.nameAr,
          roleKey: account.roles[0]?.role.key ?? 'viewer',
        }))
    : []

  // The seeded password is surfaced whenever the demo roster is enabled, so a reviewer
  // can sign in as any role with one click.
  //
  // `DEMO_ACCOUNTS_ENABLED` is the whole guard, and it is off by default: turning it on
  // is the deliberate act of saying "this instance exists to be demonstrated". A build
  // reachable by anyone must have it off — with it on, this page hands out working
  // credentials to whoever loads it.
  const demoPassword = env.demoAccountsEnabled
    ? (process.env.DEMO_ACCOUNT_PASSWORD ?? null)
    : null

  return (
    <div className="relative flex min-h-dvh flex-col">
      <div className="nabdh-grid-bg nabdh-radial pointer-events-none absolute inset-0" aria-hidden />

      <header className="relative z-10 flex items-center justify-between px-4 py-5 sm:px-8">
        <Link href="/">
          <Wordmark locale={locale} />
        </Link>
        <LanguageSwitcher compact />
      </header>

      <main className="relative z-10 flex flex-1 items-center justify-center px-4 py-8">
        <div className="grid w-full max-w-5xl items-start gap-6 lg:grid-cols-[1.05fr_1fr]">
          <Panel className="p-6 sm:p-8" glow>
            <p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-brand">
              {t('common.appName')} · {t('common.appNameLocal')}
            </p>
            <h1 className="mt-3 text-2xl font-semibold tracking-tight text-text">
              {t('auth.signInTitle')}
            </h1>
            <p className="mt-2 text-sm leading-relaxed text-text-muted">{t('auth.signInSubtitle')}</p>

            <div className="mt-7">
              <LoginForm
                next={params.next}
                demoAccounts={demoAccounts}
                demoPassword={demoPassword}
              />
            </div>

            <p className="mt-6 border-t border-border pt-5 text-xs leading-relaxed text-text-faint">
              {t('auth.securityNote')}
            </p>

            <Link
              href="/"
              className="mt-4 inline-block text-xs font-medium text-text-muted transition-colors hover:text-brand"
            >
              ← {t('auth.backToSite')}
            </Link>
          </Panel>

          <div className="space-y-4">
            <Panel className="p-6 sm:p-8">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <h2 className="text-sm font-semibold text-text">{t('common.appName')}</h2>
                <DemoDataBadge label={t('common.simulatedFull')} />
              </div>
              <p className="mt-3 text-sm leading-relaxed text-text-muted">
                {t('common.simulatedTooltip')}
              </p>

              <dl className="mt-6 space-y-3 border-t border-border pt-5">
                {(
                  [
                    ['solution.q1', 'solution.q1Body'],
                    ['solution.q2', 'solution.q2Body'],
                    ['solution.q3', 'solution.q3Body'],
                    ['solution.q4', 'solution.q4Body'],
                  ] as const
                ).map(([question, answer]) => (
                  <div key={question}>
                    <dt className="text-xs font-medium text-brand">{t(`landing.${question}`)}</dt>
                    <dd className="mt-0.5 text-xs leading-relaxed text-text-muted">
                      {t(`landing.${answer}`)}
                    </dd>
                  </div>
                ))}
              </dl>
            </Panel>
          </div>
        </div>
      </main>
    </div>
  )
}
