import { useState, type FormEvent } from 'react'
import { createFileRoute, redirect, useRouter } from '@tanstack/react-router'
import { useServerFn } from '@tanstack/react-start'
import { AuthError, login, logout } from '@netlify/identity'
import { ShieldCheck } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Logo } from '@/components/Logo'
import { getServerUser } from '@/lib/identity.functions'
import { recordSignIn } from '@/lib/notifications.functions'

// Sign-in page for the admin console. It lives outside the /admin layout so the
// guard there can send visitors here, and only accounts with admin access get in.
export const Route = createFileRoute('/admin_/login')({
  head: () => ({ meta: [{ title: 'Admin sign in — AkotoCreative SMS' }, { name: 'robots', content: 'noindex, nofollow' }] }),
  beforeLoad: async () => {
    const user = await getServerUser()
    if (user?.isAdmin) throw redirect({ to: '/admin' })
    return { signedInEmail: user?.email ?? null }
  },
  component: AdminLogin,
})

function AdminLogin() {
  const { signedInEmail } = Route.useRouteContext()
  const router = useRouter()
  const fetchServerUser = useServerFn(getServerUser)
  const [pending, setPending] = useState(false)
  const [error, setError] = useState<string | null>(
    signedInEmail ? `${signedInEmail} doesn’t have admin access. Sign in with an admin account.` : null,
  )

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (pending) return
    const fields = new FormData(event.currentTarget)
    setPending(true)
    setError(null)
    try {
      await login(String(fields.get('email')), String(fields.get('password')))
      const user = await fetchServerUser()
      if (!user?.isAdmin) {
        await logout()
        setError('That account doesn’t have admin access.')
        return
      }
      await recordSignIn().catch(() => undefined)
      await router.invalidate()
      await router.navigate({ to: '/admin' })
    } catch (err) {
      setError(
        err instanceof AuthError && (err.status === 400 || err.status === 401)
          ? 'That email and password don’t match an account.'
          : 'Something went wrong. Please try again.',
      )
    } finally {
      setPending(false)
    }
  }

  return (
    <div className="dot-grid grid min-h-screen place-items-center px-4 py-16">
      <div className="w-full max-w-sm">
        <div className="mb-6 flex items-center justify-center gap-2">
          <Logo />
          <span className="inline-flex items-center gap-1 rounded-full bg-accent px-2 py-0.5 text-xs font-semibold text-accent-foreground">
            <ShieldCheck className="size-3" aria-hidden /> Admin
          </span>
        </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-2xl font-extrabold">Admin console</h1>
          <p className="mt-2 mb-6 text-sm text-muted-foreground">Sign in with an administrator account.</p>
          <form onSubmit={submit} className="grid gap-5">
            <fieldset disabled={pending} className="grid gap-5">
              <legend className="sr-only">Admin sign in details</legend>
              <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">
                <Label htmlFor="password">Password</Label>
                <Input id="password" name="password" type="password" autoComplete="current-password" required />
              </div>
              <Button type="submit" size="lg" className="w-full">
                {pending ? 'Signing in…' : 'Sign in'}
              </Button>
            </fieldset>
            {error && (
              <p role="alert" className="text-sm text-destructive">
                {error}
              </p>
            )}
          </form>
        </div>
      </div>
    </div>
  )
}
