'use client'

import { useState } from 'react'
import type { Route } from 'next'
import { useSearchParams, useRouter } from 'next/navigation'
import { signIn } from 'next-auth/react'
import Image from 'next/image'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Mail, Loader2, CheckCircle2, AlertCircle, Lock, KeyRound, Clock } from 'lucide-react'
import { AnimatedCard } from '@/components/shared/animated-container'

type LoginMode = 'password' | 'magic-link'

export default function LoginPage() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [mode, setMode] = useState<LoginMode>('password')
  const [isLoading, setIsLoading] = useState(false)
  const [isSent, setIsSent] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const searchParams = useSearchParams()
  const router = useRouter()
  const callbackUrl = searchParams.get('callbackUrl') || '/'
  const errorParam = searchParams.get('error')
  const isExpiredLink = searchParams.get('expired') === '1'

  const handlePasswordLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)

    try {
      const result = await signIn('credentials', {
        email,
        password,
        redirect: false,
        callbackUrl,
      })

      if (result?.error) {
        setError('Invalid email or password. Please try again.')
      } else if (result?.ok) {
        // Use window.location for external redirects or callback URLs
        window.location.href = callbackUrl
      }
    } catch (err: unknown) {
      if (err instanceof Error && err.message.includes('429')) {
        setError('Too many attempts. Please wait a few minutes before trying again.')
      } else {
        setError('An unexpected error occurred. Please try again.')
      }
    } finally {
      setIsLoading(false)
    }
  }

  const handleMagicLink = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError(null)

    try {
      // Pre-check: does this email exist?
      const checkRes = await fetch('/api/auth/check-email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      })
      const checkData = await checkRes.json()
      if (!checkData.exists) {
        setError('No account found with this email address. Please check the email you used to sign up, or contact the administrator.')
        setIsLoading(false)
        return
      }

      // Get CSRF token first
      const csrfRes = await fetch('/api/auth/csrf')
      const { csrfToken } = await csrfRes.json()

      // POST directly to the signin endpoint
      const res = await fetch('/api/auth/signin/email', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          csrfToken,
          email,
          callbackUrl,
        }),
        redirect: 'manual',
      })

      // 302 redirect means success
      if (res.type === 'opaqueredirect' || res.status === 302 || res.ok) {
        setIsSent(true)
      } else {
        setError('Failed to send magic link. Please try again.')
      }
    } catch (err: unknown) {
      if (err instanceof Error && err.message.includes('429')) {
        setError('Too many attempts. Please wait a few minutes before trying again.')
      } else {
        setError('An unexpected error occurred. Please try again.')
      }
    } finally {
      setIsLoading(false)
    }
  }

  // Success state after sending magic link
  if (isSent) {
    return (
      <AnimatedCard>
      <Card className="w-full max-w-md overflow-hidden">
        <div className="h-1 w-full bg-gradient-to-r from-brand-blue via-brand-teal to-brand-blue" />
        <CardHeader className="text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-2xl bg-emerald-50 animate-in zoom-in-50 duration-300">
            <Mail className="h-8 w-8 text-green-600" />
          </div>
          <CardTitle className="text-xl">Check your email</CardTitle>
          <CardDescription className="text-base">
            We&apos;ve sent a magic link to <strong>{email}</strong>
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="rounded-lg border bg-muted/50 p-4 text-sm text-muted-foreground space-y-2">
            <p>Click the link in the email to sign in. The link will expire in 15 minutes.</p>
            <p>If you don&apos;t see it, check your spam folder.</p>
          </div>
          <div className="border-t pt-4 space-y-2">
            <Button
              variant="outline"
              className="w-full"
              onClick={() => {
                setIsSent(false)
                setError(null)
              }}
            >
              Send to a different email
            </Button>
            <p className="text-xs text-center text-muted-foreground">
              Having trouble?{' '}
              <a href="mailto:support@monaco-opc.com" className="text-primary hover:underline">
                Contact support
              </a>
            </p>
          </div>
        </CardContent>
      </Card>
      </AnimatedCard>
    )
  }

  return (
    <AnimatedCard>
    <Card className="w-full max-w-md overflow-hidden">
      <div className="h-1 w-full bg-gradient-to-r from-brand-blue via-brand-teal to-brand-blue" />
      <CardHeader className="text-center">
        <div className="flex justify-center mb-2">
          <Image
            src="/images/MOPC-blue-small.png"
            alt="MOPC"
            width={48}
            height={48}
            className="h-12 w-auto"
          />
        </div>
        <CardTitle className="text-2xl">Welcome back</CardTitle>
        <CardDescription>
          {mode === 'password'
            ? 'Sign in with your email and password'
            : 'Sign in with a magic link'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {isExpiredLink && (
          <div className="mb-4 flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm">
            <Clock className="h-4 w-4 mt-0.5 text-amber-600 shrink-0" />
            <div>
              <p className="font-medium text-amber-900">Your link has expired</p>
              <p className="text-amber-700 mt-0.5">
                Sign-in links expire after 15 minutes for security. Please sign in below or request a new magic link.
              </p>
            </div>
          </div>
        )}
        {mode === 'password' ? (
          // Password login form
          <form onSubmit={handlePasswordLogin} className="space-y-4">
            {(error || errorParam) && (
              <div className="flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive">
                <AlertCircle className="h-4 w-4 shrink-0" />
                <p>
                  {error ||
                    (errorParam === 'Verification'
                      ? 'The magic link has expired or is invalid.'
                      : errorParam === 'CredentialsSignin'
                        ? 'Invalid email or password.'
                        : 'An error occurred during sign in.')}
                </p>
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="email">Email address</Label>
              <Input
                id="email"
                type="email"
                placeholder="you@example.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                disabled={isLoading}
                autoComplete="email"
                autoFocus
              />
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label htmlFor="password">Password</Label>
                <Link
                  href={'/forgot-password' as Route}
                  className="text-sm text-muted-foreground hover:text-primary transition-colors"
                >
                  Forgot password?
                </Link>
              </div>
              <Input
                id="password"
                type="password"
                placeholder="Enter your password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                disabled={isLoading}
                autoComplete="current-password"
              />
            </div>

            <Button type="submit" className="w-full" disabled={isLoading}>
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Signing in...
                </>
              ) : (
                <>
                  <Lock className="mr-2 h-4 w-4" />
                  Sign in
                </>
              )}
            </Button>
          </form>
        ) : (
          // Magic link form
          <form onSubmit={handleMagicLink} className="space-y-4">
            {(error || errorParam) && (
              <div className="flex items-center gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive">
                <AlertCircle className="h-4 w-4 shrink-0" />
                <p>
                  {error ||
                    (errorParam === 'Verification'
                      ? 'The magic link has expired or is invalid.'
                      : 'An error occurred during sign in.')}
                </p>
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="email-magic">Email address</Label>
              <Input
                id="email-magic"
                type="email"
                placeholder="you@example.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                disabled={isLoading}
                autoComplete="email"
                autoFocus
              />
            </div>

            <Button type="submit" className="w-full" disabled={isLoading}>
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Sending...
                </>
              ) : (
                <>
                  <Mail className="mr-2 h-4 w-4" />
                  Send magic link
                </>
              )}
            </Button>

            <p className="text-sm text-muted-foreground text-center">
              We&apos;ll send you a secure link to sign in or reset your
              password.
            </p>
          </form>
        )}

        {/* Toggle between modes */}
        <div className="mt-6 border-t pt-4">
          <button
            type="button"
            className="w-full flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-primary transition-colors"
            onClick={() => {
              setMode(mode === 'password' ? 'magic-link' : 'password')
              setError(null)
            }}
          >
            {mode === 'password' ? (
              <>
                <KeyRound className="h-4 w-4" />
                Use magic link instead
              </>
            ) : (
              <>
                <Lock className="h-4 w-4" />
                Sign in with password
              </>
            )}
          </button>
          <p className="mt-3 text-xs text-muted-foreground/70 text-center">
            Don&apos;t remember which email you used?{' '}
            <a href="mailto:contact@monaco-opc.com" className="underline hover:text-primary transition-colors">
              Contact the MOPC team
            </a>
          </p>
        </div>
      </CardContent>
    </Card>
    </AnimatedCard>
  )
}
