import { useState, type FormEvent } from 'react'
import { Link, useRouter } from '@tanstack/react-router'
import { AuthError, login, requestPasswordRecovery, signup } from '@netlify/identity'
import { MailCheck } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { GoogleSignInButton } from '@/components/GoogleButton'
import { safeReturnPath } from '@/components/IdentityProvider'
import { recordSignIn } from '@/lib/notifications.functions'

type Mode = 'login' | 'signup'

function messageFor(error: unknown, mode: Mode) {
  if (error instanceof AuthError) {
    if (error.status === 401 || error.status === 400) return 'That email and password don’t match an account.'
    if (error.status === 403) return 'New sign-ups are currently closed.'
    if (error.status === 422)
      return mode === 'signup'
        ? 'Check your email address and use a password of at least 8 characters.'
        : 'Check your email and password.'
  }
  return 'Something went wrong. Please try again.'
}

// `redirect` is the page to continue on after signing in (e.g. Buy credit).
export function AuthForm({ mode, redirect }: { mode: Mode; redirect?: string }) {
  const router = useRouter()
  const next = safeReturnPath(redirect) ?? undefined
  const [state, setState] = useState<'idle' | 'pending' | 'check-email'>('idle')
  const [error, setError] = useState<string | null>(null)
  const [notice, setNotice] = useState<string | null>(null)

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (state === 'pending') return
    const fields = new FormData(event.currentTarget)
    const email = String(fields.get('email'))
    const password = String(fields.get('password'))
    setState('pending')
    setError(null)
    setNotice(null)
    try {
      if (mode === 'signup') {
        const user = await signup(email, password, { full_name: String(fields.get('name') ?? '') })
        if (!user.confirmedAt) {
          setState('check-email')
          return
        }
      } else {
        await login(email, password)
      }
      // A missed alert should never block signing in.
      await recordSignIn().catch(() => undefined)
      await router.invalidate()
      await (next ? router.navigate({ href: next }) : router.navigate({ to: '/dashboard' }))
      setState('idle')
    } catch (err) {
      setError(messageFor(err, mode))
      setState('idle')
    }
  }

  async function forgotPassword(form: HTMLFormElement | null) {
    const email = form ? String(new FormData(form).get('email') ?? '') : ''
    if (!email) {
      setError('Enter your email address first, then choose “Forgot password”.')
      return
    }
    try {
      await requestPasswordRecovery(email)
      setError(null)
      setNotice('If that email has an account, a reset link is on its way.')
    } catch {
      setError('We could not send a reset link. Please try again.')
    }
  }

  if (state === 'check-email') {
    return (
      <div className="grid gap-4 text-center" role="status">
        <MailCheck className="mx-auto size-10 text-primary" aria-hidden />
        <h2 className="text-2xl font-bold">Check your inbox</h2>
        <p className="text-muted-foreground">
          We sent you a confirmation link. Open it to activate your account, then come back to buy credit.
        </p>
      </div>
    )
  }

  return (
    <form onSubmit={submit} className="grid gap-5" id="auth-form">
      <GoogleSignInButton label={mode === 'signup' ? 'Sign up with Google' : 'Continue with Google'} next={next} />
      <fieldset disabled={state === 'pending'} className="grid gap-5">
        <legend className="sr-only">{mode === 'signup' ? 'Account details' : 'Sign in details'}</legend>
        {mode === 'signup' && (
          <div className="grid gap-2">
            <Label htmlFor="name">Business or your name</Label>
            <Input id="name" name="name" autoComplete="organization" required maxLength={80} />
          </div>
        )}
        <div className="grid gap-2">
          <Label htmlFor="email">Email</Label>
          <Input id="email" name="email" type="email" autoComplete="email" required />
        </div>
        <div className="grid gap-2">
          <div className="flex items-center justify-between">
            <Label htmlFor="password">Password</Label>
            {mode === 'login' && (
              <button
                type="button"
                className="rounded text-xs font-medium text-primary underline-offset-4 hover:underline"
                onClick={(e) => forgotPassword(e.currentTarget.form)}
              >
                Forgot password?
              </button>
            )}
          </div>
          <Input
            id="password"
            name="password"
            type="password"
            minLength={mode === 'signup' ? 8 : undefined}
            autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
            required
          />
        </div>
        <Button type="submit" size="lg" className="w-full">
          {state === 'pending'
            ? mode === 'signup'
              ? 'Creating account…'
              : 'Signing in…'
            : mode === 'signup'
              ? 'Create account'
              : 'Sign in'}
        </Button>
        {mode === 'signup' && (
          <p className="text-center text-xs text-muted-foreground">
            By creating an account you agree to our{' '}
            <Link to="/legal/$doc" params={{ doc: 'terms' }} className="font-medium text-primary underline-offset-4 hover:underline">
              Terms
            </Link>
            ,{' '}
            <Link to="/legal/$doc" params={{ doc: 'acceptable-use' }} className="font-medium text-primary underline-offset-4 hover:underline">
              Acceptable use
            </Link>{' '}
            and{' '}
            <Link to="/legal/$doc" params={{ doc: 'privacy' }} className="font-medium text-primary underline-offset-4 hover:underline">
              Privacy
            </Link>{' '}
            policies.
          </p>
        )}
      </fieldset>
      {error && (
        <p role="alert" className="text-sm text-destructive">
          {error}
        </p>
      )}
      {notice && (
        <p role="status" className="text-sm text-primary">
          {notice}
        </p>
      )}
      <p className="text-center text-sm text-muted-foreground">
        {mode === 'signup' ? (
          <>
            Already have an account?{' '}
            <Link to="/login" search={next ? { redirect: next } : {}} className="font-medium text-primary underline-offset-4 hover:underline">
              Sign in
            </Link>
          </>
        ) : (
          <>
            New to AkotoCreative SMS?{' '}
            <Link to="/signup" search={next ? { redirect: next } : {}} className="font-medium text-primary underline-offset-4 hover:underline">
              Create an account
            </Link>
          </>
        )}
      </p>
    </form>
  )
}

export function AuthShell({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
  return (
    <div className="dot-grid">
      <div className="mx-auto grid max-w-content gap-10 px-4 py-16 sm:px-6 lg:grid-cols-[1fr_28rem] lg:items-center">
        <div className="hidden lg:block">
          <p className="font-display text-sm font-bold uppercase tracking-[0.2em] text-primary">AkotoCreative SMS</p>
          <p className="mt-4 max-w-md font-display text-5xl font-extrabold leading-[1.05]">
            One message. <span className="text-primary">Thousands</span> of phones.
          </p>
          <p className="mt-4 max-w-md text-muted-foreground">
            Top up with MTN MoMo, Telecel Cash, AirtelTigo Money or card. Credits never expire.
          </p>
        </div>
        <div className="rounded-2xl border bg-card p-8 shadow-[0_24px_60px_-30px_color-mix(in_oklch,var(--primary)_45%,transparent)]">
          <h1 className="text-3xl font-extrabold">{title}</h1>
          <p className="mt-2 mb-8 text-muted-foreground">{subtitle}</p>
          {children}
        </div>
      </div>
    </div>
  )
}
