'use client'

import { useState, useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import Link from 'next/link'
import Image from 'next/image'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { Loader2, ArrowRight, Eye, EyeOff, CheckCircle } from 'lucide-react'

// Logo Component
function Logo() {
  return (
    <Image
      src="/pounce-logo.png"
      alt="pounce"
      width={120}
      height={60}
      className="w-28 h-auto"
    />
  )
}

// OAuth Icons
function GoogleIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <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.93l2.85-2.22.81-.62z" 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>
  )
}

function GitHubIcon({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
    </svg>
  )
}

function LoginForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { login } = useStore()
  
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)
  const [oauthProviders, setOauthProviders] = useState({ google_enabled: false, github_enabled: false })
  const [verified, setVerified] = useState(false)

  const sanitizeRedirect = (value: string | null | undefined): string => {
    const fallback = '/terminal/radar'
    if (!value) return fallback
    const v = value.trim()
    if (!v.startsWith('/')) return fallback
    if (v.startsWith('//')) return fallback
    if (v.includes('://')) return fallback
    if (v.includes('\\')) return fallback
    if (v.length > 2048) return fallback
    return v
  }

  // Get redirect URL from query params or localStorage (set during registration)
  const paramRedirect = searchParams.get('redirect')
  const [redirectTo, setRedirectTo] = useState(sanitizeRedirect(paramRedirect))
  
  // Check localStorage for redirect (set during registration before email verification)
  useEffect(() => {
    const storedRedirect = localStorage.getItem('pounce_redirect_after_login')
    if (storedRedirect && !paramRedirect) {
      setRedirectTo(sanitizeRedirect(storedRedirect))
    }
  }, [paramRedirect])
  
  // Check for verified status
  useEffect(() => {
    if (searchParams.get('verified') === 'true') {
      setVerified(true)
    }
    if (searchParams.get('error')) {
      setError(searchParams.get('error') === 'oauth_failed' ? 'OAuth authentication failed. Please try again.' : 'Authentication failed')
    }
  }, [searchParams])

  // Load OAuth providers
  useEffect(() => {
    api.getOAuthProviders().then(setOauthProviders).catch(() => {})
  }, [])

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

    try {
      await login(email, password)
      
      // Check if email is verified
      const user = await api.getMe()
      if (!user.is_verified) {
        // Redirect to verify-email page if not verified
        router.push(`/verify-email?email=${encodeURIComponent(email)}`)
        return
      }
      
      // Clear stored redirect (was set during registration)
      localStorage.removeItem('pounce_redirect_after_login')
      
      // Redirect to intended destination or dashboard
      router.push(sanitizeRedirect(redirectTo))
    } catch (err: unknown) {
      console.error('Login error:', err)
      if (err instanceof Error) {
        setError(err.message || 'Authentication failed')
      } else if (typeof err === 'object' && err !== null) {
        if ('detail' in err) {
          setError(String((err as { detail: unknown }).detail))
        } else if ('message' in err) {
          setError(String((err as { message: unknown }).message))
        } else {
          setError('Authentication failed. Please try again.')
        }
      } else if (typeof err === 'string') {
        setError(err)
      } else {
        setError('Authentication failed. Please try again.')
      }
    } finally {
      setLoading(false)
    }
  }

  // Generate register link with redirect preserved
  const registerLink = redirectTo !== '/terminal/radar' 
    ? `/register?redirect=${encodeURIComponent(redirectTo)}`
    : '/register'

  return (
    <div className="relative w-full max-w-sm animate-fade-in">
      {/* Logo */}
      <Link href="/" className="flex justify-center mb-12 sm:mb-16 hover:opacity-80 transition-opacity duration-300">
        <Logo />
      </Link>

      {/* Header */}
      <div className="text-center mb-8 sm:mb-10">
        <h1 className="font-display text-[2rem] sm:text-[2.5rem] md:text-[3rem] leading-[1.1] tracking-[-0.03em] text-foreground mb-2 sm:mb-3">
          Back to the hunt.
        </h1>
        <p className="text-body-sm sm:text-body text-foreground-muted">
          Sign in to your account
        </p>
      </div>

      {/* Verified Message */}
      {verified && (
        <div className="mb-6 p-4 bg-accent/10 border border-accent/20 rounded-2xl flex items-center gap-3">
          <CheckCircle className="w-5 h-5 text-accent shrink-0" />
          <p className="text-sm text-accent">Email verified successfully! You can now sign in.</p>
        </div>
      )}

      {/* Form */}
      <form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
        {error && (
          <div className="p-3 sm:p-4 bg-danger-muted border border-danger/20 rounded-2xl">
            <p className="text-danger text-body-xs sm:text-body-sm text-center">{error}</p>
          </div>
        )}

        <div className="space-y-2.5 sm:space-y-3">
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Email address"
            required
            autoComplete="email"
            className="input-elegant text-body-sm sm:text-body"
          />
          <div className="relative">
            <input
              type={showPassword ? 'text' : 'password'}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Password"
              required
              minLength={8}
              autoComplete="current-password"
              className="input-elegant text-body-sm sm:text-body pr-12"
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute right-3 sm:right-4 top-1/2 -translate-y-1/2 text-foreground-muted hover:text-foreground transition-colors duration-200"
              aria-label={showPassword ? 'Hide password' : 'Show password'}
            >
              {showPassword ? (
                <EyeOff className="w-4 h-4 sm:w-5 sm:h-5" />
              ) : (
                <Eye className="w-4 h-4 sm:w-5 sm:h-5" />
              )}
            </button>
          </div>
        </div>

        <div className="flex justify-end">
          <Link 
            href="/forgot-password" 
            className="text-body-xs sm:text-body-sm text-foreground-muted hover:text-accent transition-colors duration-300"
          >
            Forgot password?
          </Link>
        </div>

        <button
          type="submit"
          disabled={loading}
          className="w-full py-3 sm:py-4 bg-foreground text-background text-ui-sm sm:text-ui font-medium rounded-xl
                     hover:bg-foreground/90 disabled:opacity-50 disabled:cursor-not-allowed
                     transition-all duration-300 flex items-center justify-center gap-2 sm:gap-2.5"
        >
          {loading ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : (
            <>
              Continue
              <ArrowRight className="w-3.5 sm:w-4 h-3.5 sm:h-4" />
            </>
          )}
        </button>
      </form>

      {/* OAuth Buttons */}
      {(oauthProviders.google_enabled || oauthProviders.github_enabled) && (
        <div className="mt-6">
          {/* Divider */}
          <div className="relative mb-6">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-border" />
            </div>
            <div className="relative flex justify-center text-xs">
              <span className="px-4 bg-background text-foreground-muted">or continue with</span>
            </div>
          </div>
          
          <div className="space-y-3">
            {oauthProviders.google_enabled && (
              <a
                href={api.getGoogleLoginUrl(redirectTo)}
                className="w-full py-3 sm:py-3.5 bg-[#24292e] text-white text-sm font-medium rounded-xl
                           hover:bg-[#2f363d] border border-[#24292e]
                           transition-all duration-300 flex items-center justify-center gap-3"
              >
                <GoogleIcon className="w-5 h-5" />
                Continue with Google
              </a>
            )}
            {oauthProviders.github_enabled && (
              <a
                href={api.getGitHubLoginUrl(redirectTo)}
                className="w-full py-3 sm:py-3.5 bg-[#24292e] text-white text-sm font-medium rounded-xl
                           hover:bg-[#2f363d] border border-[#24292e]
                           transition-all duration-300 flex items-center justify-center gap-3"
              >
                <GitHubIcon className="w-5 h-5" />
                Continue with GitHub
              </a>
            )}
          </div>
        </div>
      )}

      {/* Register Link */}
      <p className="mt-8 sm:mt-10 text-center text-body-xs sm:text-body-sm text-foreground-muted">
        Don&apos;t have an account?{' '}
        <Link href={registerLink} className="text-foreground hover:text-accent transition-colors duration-300">
          Create one
        </Link>
      </p>
    </div>
  )
}

export default function LoginPage() {
  return (
    <div className="min-h-screen flex items-center justify-center px-4 sm:px-6 py-8 sm:py-12 relative">
      {/* Ambient glow */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-1/4 left-1/2 -translate-x-1/2 w-[400px] h-[300px] bg-accent/[0.02] rounded-full blur-3xl" />
      </div>
      
      <Suspense fallback={
        <div className="w-5 h-5 border-2 border-accent border-t-transparent rounded-full animate-spin" />
      }>
        <LoginForm />
      </Suspense>
    </div>
  )
}
