'use client'

import { useEffect } from 'react'
import { useAdminRouter } from './router/index.js'
import { ThemeProvider } from './components/ThemeProvider.js'
import { ISOLATION_STYLE, useRobotsNoIndex } from './lib/root-chrome.js'
import { Login, type CaptchaConfig } from './views/Login.js'
import { SetupWizard } from './views/SetupWizard.js'
import { ForgotPassword } from './views/ForgotPassword.js'
import { ResetPassword } from './views/ResetPassword.js'

export interface LoginRootProps {
  config?: any
  /** Current session, if any. Authenticated visitors are sent to `adminPath`. */
  session?: any
  /** Mount path of this login screen (default: '/securelogin'). */
  basePath?: string
  /**
   * Where the admin app lives (default: '/admin'). Users are sent here after
   * signing in — and immediately, if they arrive already authenticated.
   */
  adminPath?: string
  setupRequired?: boolean
  onSetupComplete?: (data: {
    name: string
    email: string
    password: string
  }) => Promise<{ success: boolean; error?: string }>
  onLogin: (
    email: string,
    password: string,
    captchaToken?: string,
  ) => Promise<{
    success: boolean
    error?: string
    requiresTOTP?: boolean
    mfaPendingToken?: string
  }>
  /** Completes the TOTP second-factor step for accounts with MFA enabled. */
  onVerifyTotp?: (
    mfaPendingToken: string,
    code: string,
  ) => Promise<{ success: boolean; error?: string }>
  captchaConfig?: CaptchaConfig
  /**
   * Called once a session exists (after login, or on arrival while already
   * signed in). Defaults to a full-page navigation to `adminPath` — the admin
   * app is a separate route mount, so a client-side route push can't reach it.
   */
  onAuthenticated?: (adminPath: string) => void
}

/**
 * Standalone mount for the unauthenticated auth screens on split-login
 * installs: login (+ MFA), setup wizard, forgot/reset password. Pair it with
 * `<AdminRoot loginPath>` so the admin mount itself stops rendering a login
 * form for signed-out visitors.
 *
 * Routes under `basePath`:
 * - `/` — login (or the setup wizard while `setupRequired`)
 * - `/setup` — setup wizard (first-run; falls back to login once setup is done)
 * - `/forgot-password`, `/reset-password?token=…` — recovery flows; emailed
 *   reset/invite links point here when `config.admin.loginPath` is set.
 */
export function LoginRoot({
  config,
  session,
  basePath = '/securelogin',
  adminPath = '/admin',
  setupRequired,
  onSetupComplete,
  onLogin,
  onVerifyTotp,
  captchaConfig,
  onAuthenticated,
}: LoginRootProps) {
  const defaultDarkMode = config?.admin?.branding?.darkMode

  useRobotsNoIndex()

  return (
    <div style={ISOLATION_STYLE} className="actuate-admin">
      <ThemeProvider defaultDarkMode={defaultDarkMode}>
        <LoginShell
          config={config}
          session={session}
          basePath={basePath}
          adminPath={adminPath}
          setupRequired={setupRequired}
          onSetupComplete={onSetupComplete}
          onLogin={onLogin}
          onVerifyTotp={onVerifyTotp}
          captchaConfig={captchaConfig}
          onAuthenticated={onAuthenticated}
        />
      </ThemeProvider>
    </div>
  )
}

function LoginShell({
  config,
  session,
  basePath = '/securelogin',
  adminPath = '/admin',
  setupRequired,
  onSetupComplete,
  onLogin,
  onVerifyTotp,
  captchaConfig,
  onAuthenticated,
}: LoginRootProps) {
  const { navigate, matchRoute } = useAdminRouter(basePath, '/')

  // Already signed in (or just signed in): hand off to the admin app. The
  // admin is a separate route mount, so this must be a full-page navigation.
  const authenticated = Boolean(session) && !setupRequired
  useEffect(() => {
    if (!authenticated) return
    if (onAuthenticated) {
      onAuthenticated(adminPath)
      return
    }
    if (typeof window !== 'undefined') {
      window.location.replace(adminPath)
    }
  }, [authenticated, adminPath, onAuthenticated])

  if (authenticated) {
    return (
      <div className="bg-background flex min-h-screen items-center justify-center">
        <p className="text-muted-foreground text-sm" role="status">
          Signed in — taking you to the admin…
        </p>
      </div>
    )
  }

  if (setupRequired && onSetupComplete) {
    return (
      <SetupWizard
        onComplete={onSetupComplete}
        siteName={config?.admin?.branding?.name ?? 'Actuate CMS'}
      />
    )
  }

  if (matchRoute('/forgot-password')) {
    return <ForgotPassword onNavigate={navigate} />
  }

  if (matchRoute('/reset-password')) {
    const params = new URLSearchParams(typeof window !== 'undefined' ? window.location.search : '')
    return <ResetPassword onNavigate={navigate} token={params.get('token')} />
  }

  return (
    <Login
      onLogin={onLogin}
      onVerifyTotp={onVerifyTotp}
      onNavigate={navigate}
      captchaConfig={captchaConfig}
      branding={config?.admin?.branding}
    />
  )
}
