'use client'

import { useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { signIn } from 'next-auth/react'
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 } from 'lucide-react'

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 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 {
      // 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 (
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-green-100 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>
    )
  }

  return (
    <Card className="w-full max-w-md">
      <CardHeader className="text-center">
        <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>
        {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>
                <button
                  type="button"
                  className="text-sm text-muted-foreground hover:text-primary transition-colors"
                  onClick={() => {
                    setMode('magic-link')
                    setError(null)
                  }}
                >
                  Forgot password?
                </button>
              </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>
        </div>
      </CardContent>
    </Card>
  )
}
