'use client'

import { Suspense, useState } from 'react'
import { signIn } from 'next-auth/react'
import { useRouter, useSearchParams } from 'next/navigation'
import BrandName from '@/app/BrandName'
import {
  FieldGroup,
  FieldLabel,
  PrimaryButton,
  SecondaryButton,
  TextField,
} from '@/app/FormFields'
import ThemeToggle from '@/app/ThemeToggle'

type Step = 'email' | 'waitlist' | 'expired'

const devLoginOptions = [
  { label: 'Expert', email: 'expert@example.com' },
  { label: 'Line manager', email: 'factorymgr1@example.com' },
  { label: 'Admin', email: 'admin@example.com' },
]

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

function LoginForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const callbackUrl = searchParams.get('callbackUrl') ?? '/'
  const authError = searchParams.get('error')
  const initialEmail = searchParams.get('email')?.toLowerCase().trim() ?? ''
  const [step, setStep] = useState<Step>(
    authError === 'Verification' ? 'expired' : authError ? 'waitlist' : 'email'
  )
  const [email, setEmail] = useState(initialEmail)
  const [loadingLabel, setLoadingLabel] = useState<string | null>(null)
  const [googleLoading, setGoogleLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const loading = Boolean(loadingLabel)

  async function sendMagicLink(emailAddress: string) {
    setLoadingLabel('Sending sign-in link…')
    const result = await signIn('nodemailer', {
      email: emailAddress,
      callbackUrl,
      redirect: false,
    })
    if (typeof result === 'object' && result?.error) {
      setError('Unable to send sign-in link. Please try again.')
      return false
    }
    return true
  }

  async function handleEmailSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoadingLabel('Checking…')
    setError(null)

    const trimmed = email.toLowerCase().trim()

    try {
      const res = await fetch(`/api/auth/check-email?email=${encodeURIComponent(trimmed)}`)
      const { exists } = await res.json()

      if (exists) {
        const ok = await sendMagicLink(trimmed)
        if (ok) router.push(`/login/verify?email=${encodeURIComponent(trimmed)}`)
      } else {
        // Fire-and-forget — don't let a redirect or network error block the UX
        fetch('/api/waitlist', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email: trimmed }),
        }).catch(() => {})
        setStep('waitlist')
      }
    } catch {
      setError('Something went wrong. Please try again.')
    } finally {
      setLoadingLabel(null)
    }
  }

  return (
    <main className="relative flex min-h-screen items-center justify-center bg-zinc-50 px-4 text-zinc-950 dark:bg-zinc-950 dark:text-zinc-100">
      <div className="absolute top-4 right-4">
        <ThemeToggle />
      </div>
      <div className="w-full max-w-sm rounded-lg border border-zinc-200 bg-white p-8 shadow-sm dark:border-zinc-800 dark:bg-zinc-900">

        {step === 'expired' ? (
          <>
            <h1 className="mb-1 text-xl font-semibold text-zinc-950 dark:text-white">Sign-in link expired</h1>
            <p className="mb-4 text-sm text-zinc-600 dark:text-zinc-400">
              Your sign-in link has expired or was already used. Please request a new one.
            </p>
            <button
              type="button"
              onClick={() => { setStep('email'); setError(null) }}
              className="mt-2 w-full rounded-md px-4 py-2 text-sm font-medium text-zinc-600 transition hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
            >
              ← Request a new link
            </button>
          </>
        ) : step === 'email' ? (
          <>
            <h1 className="mb-1 text-xl font-semibold text-zinc-950 dark:text-white">Sign in to <BrandName /></h1>
            <p className="mb-6 text-sm text-zinc-600 dark:text-zinc-400">
              Enter your email and we&apos;ll send you a magic link.
            </p>

            {process.env.NODE_ENV !== 'production' && (
              <div className="mb-5 rounded-md border border-amber-300 bg-amber-50 p-3 dark:border-amber-400/40 dark:bg-amber-300/10">
                <p className="mb-2 text-xs font-medium uppercase tracking-wide text-amber-800 dark:text-amber-200">Dev bypass</p>
                <div className="grid gap-2 sm:grid-cols-3">
                  {devLoginOptions.map((option) => (
                    <a
                      key={option.email}
                      href={`/api/dev-login?email=${encodeURIComponent(option.email)}`}
                      className="rounded-lg bg-amber-700 px-3 py-2 text-center text-sm font-semibold text-white transition hover:bg-amber-800 dark:bg-amber-200 dark:text-zinc-950 dark:hover:bg-amber-100"
                    >
                      {option.label}
                    </a>
                  ))}
                </div>
              </div>
            )}

            <SecondaryButton
              type="button"
              disabled={googleLoading || loading}
              onClick={() => { setGoogleLoading(true); signIn('google', { callbackUrl }) }}
              className="flex w-full items-center justify-center gap-2"
            >
              {googleLoading
                ? <span className="inline-block h-4 w-4 rounded-full border-2 border-zinc-400 border-t-transparent animate-spin" aria-hidden="true" />
                : <svg viewBox="0 0 24 24" className="h-4 w-4" aria-hidden="true">
                    <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                    <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                    <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05"/>
                    <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
                  </svg>
              }
              {googleLoading ? 'Redirecting…' : 'Sign in with Google'}
            </SecondaryButton>

            <div className="relative my-5">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-zinc-200 dark:border-zinc-700" />
              </div>
              <div className="relative flex justify-center">
                <span className="bg-white px-2 text-xs text-zinc-400 dark:bg-zinc-900 dark:text-zinc-500">or continue with email</span>
              </div>
            </div>

            <form onSubmit={handleEmailSubmit} className="space-y-4">
              <FieldGroup>
                <FieldLabel htmlFor="email">Email address</FieldLabel>
                <TextField
                  id="email"
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@example.com"
                />
              </FieldGroup>
              {error ? <p className="text-sm text-red-700 dark:text-red-300">{error}</p> : null}
              <PrimaryButton
                type="submit"
                loading={loading}
                className="w-full"
              >
                {loadingLabel ?? 'Continue'}
              </PrimaryButton>
            </form>
          </>
        ) : (
          /* step === 'waitlist' */
          <>
            <h1 className="mb-1 text-xl font-semibold text-zinc-950 dark:text-white">Access is by invite only</h1>
            {email ? (
              <p className="mb-4 text-sm text-zinc-600 dark:text-zinc-400">
                <span className="font-medium text-zinc-800 dark:text-zinc-200">{email}</span> isn&apos;t on the list yet.
                We&apos;ve added you to our waitlist and will be in touch when access opens up.
              </p>
            ) : (
              <p className="mb-4 text-sm text-zinc-600 dark:text-zinc-400">
                Your account isn&apos;t on the list yet. We&apos;ve noted your interest and will be in touch when access opens up.
              </p>
            )}
            <p className="text-sm text-zinc-500 dark:text-zinc-500">
              If you think this is a mistake, contact your administrator.
            </p>
            <button
              type="button"
              onClick={() => { setStep('email'); setError(null) }}
              className="mt-6 w-full rounded-md px-4 py-2 text-sm font-medium text-zinc-600 transition hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
            >
              ← Try a different email
            </button>
          </>
        )}
      </div>
    </main>
  )
}
