'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'

import { useActionState } from 'react'
import Link from 'next/link'
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
import { signIn } from '../actions'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { GoogleAuthButton, GoogleAuthError } from '@/components/auth/google-auth-button'
import { RecaptchaScript, recaptchaToken } from '@/lib/security/recaptcha-client'

export default function LoginPage() {
  return (
    <Suspense>
      <LoginForm />
    </Suspense>
  )
}

/**
 * Sign in with an emailed code instead of a password (Nash, 2026-09-23) — how
 * a moderator invited to one page gets in, and anyone who signed up through an
 * invitation link. The answer is the same whether or not the address exists.
 */
function EmailCodeSignIn() {
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const [email, setEmail] = useState('')
  const [code, setCode] = useState('')
  const [sent, setSent] = useState(false)
  const [busy, setBusy] = useState(false)
  const [note, setNote] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [connected, setConnected] = useState<{ next: string; roles: string[] } | null>(null)

  async function call(body: Record<string, unknown>) {
    const r = await fetch('/api/auth/email-code', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
    const json = await r.json().catch(() => ({}))
    if (!r.ok) throw new Error(json.error ?? 'Something went wrong.')
    return json as { message?: string; dev_code?: string; next?: string; historical?: { connected: boolean; roles: string[] } }
  }
  async function start() {
    setBusy(true); setError(null)
    try {
      const captchaToken = await recaptchaToken('email_code_start')
      const j = await call({ op: 'start', email, captchaToken })
      setSent(true)
      setNote(j.dev_code ? `${j.message} Development code: ${j.dev_code}` : (j.message ?? null))
    } catch (e) { setError(e instanceof Error ? e.message : 'Could not send the code.') } finally { setBusy(false) }
  }
  async function verify() {
    setBusy(true); setError(null)
    try {
      const j = await call({ op: 'verify', email, code })
      // A claimed historical identity is announced before the dashboard opens (§42).
      if (j.historical?.connected) { setConnected({ next: j.next ?? '/dashboard', roles: j.historical.roles }); return }
      router.push(j.next ?? '/dashboard'); router.refresh()
    } catch (e) { setError(e instanceof Error ? e.message : 'That code is not valid.') } finally { setBusy(false) }
  }

  if (!open) {
    return (
      <p className="mt-4 border-t pt-4 text-center text-sm">
        <button type="button" onClick={() => setOpen(true)} className="font-medium text-neutral-900 underline">Email me a sign-in code instead</button>
      </p>
    )
  }
  if (connected) {
    return (
      <div className="mt-4 space-y-3 border-t pt-4">
        <p className="text-sm font-semibold">Your historical HeavyHaul/Synchron activity has been connected.</p>
        {connected.roles.length > 0 && (
          <ul className="space-y-1 text-sm text-neutral-700">{connected.roles.map((r) => <li key={r}>{r}</li>)}</ul>
        )}
        <p className="text-xs text-neutral-500">{connected.roles.length > 1 ? 'Use Switch Mode in the menu to move between them.' : 'Your historical trips are in your dashboard.'}</p>
        <Button type="button" className="w-full" onClick={() => { router.push(connected.next); router.refresh() }}>Continue</Button>
      </div>
    )
  }
  return (
    <div className="mt-4 space-y-3 border-t pt-4">
      <p className="text-sm font-semibold">Sign in with an emailed code</p>
      <div className="space-y-2">
        <Label htmlFor="code-email">Email</Label>
        <Input id="code-email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" autoComplete="email" />
      </div>
      {sent && (
        <div className="space-y-2">
          <Label htmlFor="code">Six-digit code</Label>
          <Input id="code" inputMode="numeric" value={code} onChange={(e) => setCode(e.target.value)} placeholder="123456" />
        </div>
      )}
      {note && <p className="rounded-lg bg-neutral-50 p-2 text-xs text-neutral-600">{note}</p>}
      {error && <Alert variant="destructive"><AlertDescription>{error}</AlertDescription></Alert>}
      <div className="flex gap-2">
        {!sent ? (
          <Button type="button" className="w-full" disabled={busy || !email.includes('@')} onClick={start}>{busy ? 'Sending…' : 'Send me a code'}</Button>
        ) : (
          <>
            <Button type="button" className="w-full" disabled={busy || code.trim().length < 6} onClick={verify}>{busy ? 'Checking…' : 'Sign in'}</Button>
            <Button type="button" variant="outline" disabled={busy} onClick={start}>Resend</Button>
          </>
        )}
      </div>
      <p className="text-center text-xs"><button type="button" onClick={() => { setOpen(false); setSent(false); setCode(''); setNote(null); setError(null) }} className="text-neutral-500 underline">Use a password instead</button></p>
    </div>
  )
}

/** Portal labels for the role-specific entrances on the landing page. */
const PORTALS: Record<string, { title: string; tagline: string }> = {
  broker: { title: 'Broker Portal', tagline: 'Stop chasing permits. Start seeing the trip.' },
  carrier: {
    title: 'Carrier Control Tower',
    tagline: 'Every permit, every trip, every warning — in one place.',
  },
  driver: { title: 'Driver Portal', tagline: 'Ask questions about your permit before you move.' },
}

/**
 * Username + password only. Role switching for pilot testing happens AFTER
 * sign-in, in the header bar (AUTH_ROLE_SWITCH) — not here.
 */
function LoginForm() {
  const [state, action, pending] = useActionState(async (previous: { error?: string } | undefined, formData: FormData) => {
    try {
      formData.set('recaptchaToken', await recaptchaToken('password_login') ?? '')
      return await signIn(previous, formData)
    } catch (cause) {
      return { error: cause instanceof Error ? cause.message : 'Security verification failed.' }
    }
  }, undefined)
  const params = useSearchParams()
  const next = params.get('next') ?? ''
  const portal = PORTALS[params.get('role') ?? '']

  return (
    <main className="flex min-h-screen items-center justify-center bg-neutral-50 p-4">
      <RecaptchaScript />
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <div className="mx-auto mb-2 grid h-11 w-11 place-items-center rounded-xl bg-[#0f1b2d] text-lg font-extrabold text-[#f5a623]">
            H
          </div>
          {portal && (
            <span className="mx-auto mb-1 rounded-full bg-[#0f1b2d] px-3 py-1 text-xs font-bold text-[#f5a623]">
              {portal.title}
            </span>
          )}
          <CardTitle className="text-xl">Sign in to HeavyHaul Agent</CardTitle>
          <CardDescription>
            {portal?.tagline ?? 'The shared workspace for oversize trips'}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <GoogleAuthError />
          <div className="mb-4"><GoogleAuthButton mode="login" next={next} /></div>
          <form action={action} className="space-y-4">
            <input type="hidden" name="next" value={next} />
            {state?.error && (
              <Alert variant="destructive">
                <AlertDescription>{state.error}</AlertDescription>
              </Alert>
            )}
            <div className="space-y-2">
              <Label htmlFor="username">Username</Label>
              <Input id="username" name="username" type="text" required autoComplete="username" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <Input id="password" name="password" type="password" required autoComplete="current-password" />
            </div>
            <Button type="submit" className="w-full" disabled={pending}>
              {pending ? 'Signing in…' : 'Sign in'}
            </Button>
            <p className="text-center text-sm text-neutral-500">
              New here?{' '}
              <Link href="/signup" className="font-medium text-neutral-900 underline">
                Create an account
              </Link>
            </p>
          </form>
          <EmailCodeSignIn />
        </CardContent>
      </Card>
    </main>
  )
}
