'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'
import clsx from 'clsx'

// Logo Component
function Logo() {
  return (
    <Image
      src="/pounce-puma.png"
      alt="pounce"
      width={120}
      height={120}
      className="w-20 h-20 object-contain drop-shadow-[0_0_15px_rgba(16,185,129,0.3)]"
    />
  )
}

// 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/hunt'
    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)
      
      // Clear stored redirect (was set during registration)
      localStorage.removeItem('pounce_redirect_after_login')
      
      // Redirect to intended destination or dashboard
      // Note: Email verification is enforced by the backend if REQUIRE_EMAIL_VERIFICATION=true
      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/hunt' 
    ? `/register?redirect=${encodeURIComponent(redirectTo)}`
    : '/register'

  return (
    <div className="w-full max-w-[400px] animate-fade-in relative z-10">
      {/* Card Container */}
      <div className="bg-[#050505] border border-white/10 relative p-8 shadow-2xl">
        {/* Tech Corners */}
        <div className="absolute -top-px -left-px w-4 h-4 border-t border-l border-white/40" />
        <div className="absolute -top-px -right-px w-4 h-4 border-t border-r border-white/40" />
        <div className="absolute -bottom-px -left-px w-4 h-4 border-b border-l border-white/40" />
        <div className="absolute -bottom-px -right-px w-4 h-4 border-b border-r border-white/40" />

        {/* Logo */}
        <Link href="/" className="flex justify-center mb-8 hover:opacity-80 transition-opacity duration-300">
          <Logo />
        </Link>

        {/* Header */}
        <div className="text-center mb-10">
          <span className="text-[10px] font-mono text-accent uppercase tracking-[0.2em] mb-2 block flex items-center justify-center gap-2">
             <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
             Access Granted
          </span>
          <h1 className="font-display text-3xl text-white mb-2 tracking-tight">
            Welcome back.
          </h1>
          <p className="text-xs font-mono text-white/40">
            Authenticate to access the terminal.
          </p>
        </div>

        {/* Verified Message */}
        {verified && (
          <div className="mb-6 p-4 bg-accent/5 border border-accent/20 flex items-center gap-3">
            <CheckCircle className="w-5 h-5 text-accent shrink-0" />
            <p className="text-xs font-mono text-accent">Email verified. System access ready.</p>
          </div>
        )}

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-6">
          {error && (
            <div className="p-3 bg-red-500/10 border border-red-500/20">
              <p className="text-red-500 text-xs font-mono text-center uppercase tracking-wider">{error}</p>
            </div>
          )}

          <div className="space-y-4">
            <div className="group">
                <label className="text-[10px] font-mono text-white/40 uppercase tracking-widest mb-2 block group-focus-within:text-white/70 transition-colors">Email Address</label>
                <input
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="OPERATOR@POUNCE.IO"
                    required
                    autoComplete="email"
                    className="w-full bg-[#0A0A0A] border border-white/10 px-4 py-3 text-white font-mono text-sm placeholder:text-white/20 focus:outline-none focus:border-accent transition-all rounded-none"
                />
            </div>
            
            <div className="group relative">
                <label className="text-[10px] font-mono text-white/40 uppercase tracking-widest mb-2 block group-focus-within:text-white/70 transition-colors">Passcode</label>
                <div className="relative">
                    <input
                        type={showPassword ? 'text' : 'password'}
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        placeholder="••••••••"
                        required
                        minLength={8}
                        autoComplete="current-password"
                        className="w-full bg-[#0A0A0A] border border-white/10 px-4 py-3 text-white font-mono text-sm placeholder:text-white/20 focus:outline-none focus:border-accent transition-all rounded-none pr-12"
                    />
                    <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-4 top-1/2 -translate-y-1/2 text-white/30 hover:text-white transition-colors"
                        aria-label={showPassword ? 'Hide password' : 'Show password'}
                    >
                        {showPassword ? (
                        <EyeOff className="w-4 h-4" />
                        ) : (
                        <Eye className="w-4 h-4" />
                        )}
                    </button>
                </div>
            </div>
          </div>

          <div className="flex justify-end">
            <Link 
              href="/forgot-password" 
              className="text-[10px] font-mono text-white/40 hover:text-accent uppercase tracking-wider transition-colors"
            >
              Lost Credentials?
            </Link>
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full py-4 bg-white text-black text-xs font-bold uppercase tracking-[0.2em] hover:bg-accent transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-3"
            style={{ clipPath: 'polygon(10px 0, 100% 0, 100% 100%, 0 100%, 0 10px)' }}
          >
            {loading ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <>
                Initialize Session
                <ArrowRight className="w-4 h-4" />
              </>
            )}
          </button>
        </form>

        {/* OAuth Buttons */}
        {(oauthProviders.google_enabled || oauthProviders.github_enabled) && (
          <div className="mt-8">
            <div className="relative mb-8">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-white/10" />
              </div>
              <div className="relative flex justify-center">
                <span className="px-4 bg-[#050505] text-[10px] font-mono text-white/30 uppercase tracking-widest">Alternative Access</span>
              </div>
            </div>
            
            <div className="space-y-3">
              {oauthProviders.google_enabled && (
                <a
                  href={api.getGoogleLoginUrl(redirectTo)}
                  className="w-full py-3 bg-[#0A0A0A] border border-white/10 text-white text-xs font-mono uppercase tracking-wide hover:bg-white/5 hover:border-white/30 transition-all flex items-center justify-center gap-3"
                >
                  <GoogleIcon className="w-4 h-4" />
                  Google
                </a>
              )}
              {oauthProviders.github_enabled && (
                <a
                  href={api.getGitHubLoginUrl(redirectTo)}
                  className="w-full py-3 bg-[#0A0A0A] border border-white/10 text-white text-xs font-mono uppercase tracking-wide hover:bg-white/5 hover:border-white/30 transition-all flex items-center justify-center gap-3"
                >
                  <GitHubIcon className="w-4 h-4" />
                  GitHub
                </a>
              )}
            </div>
          </div>
        )}

        {/* Register Link */}
        <div className="mt-8 pt-8 border-t border-white/10 text-center">
          <p className="text-xs font-mono text-white/40">
            No clearance?{' '}
            <Link href={registerLink} className="text-white hover:text-accent border-b border-white/20 hover:border-accent transition-all pb-0.5 ml-1">
              Request Access
            </Link>
          </p>
        </div>
      </div>
    </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 bg-[#020202] overflow-hidden">
      {/* Living Background Atmosphere */}
      <div className="fixed inset-0 pointer-events-none overflow-hidden">
        <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.04] mix-blend-overlay z-10" />
        
        {/* Animated Orbs */}
        <div className="absolute top-[-10%] left-[-10%] w-[60vw] h-[60vw] bg-accent/10 rounded-full blur-[120px] animate-pulse-slow mix-blend-screen" />
        <div className="absolute bottom-[-10%] right-[-10%] w-[50vw] h-[50vw] bg-purple-500/10 rounded-full blur-[150px] animate-pulse-slower mix-blend-screen" />
        <div className="absolute top-[40%] left-[40%] w-[40vw] h-[40vw] bg-blue-500/5 rounded-full blur-[100px] animate-blob mix-blend-screen" />
        
        {/* Grid Overlay */}
        <div 
          className="absolute inset-0 opacity-[0.03] z-0"
          style={{
            backgroundImage: `linear-gradient(rgba(255,255,255,0.3) 0.5px, transparent 0.5px), linear-gradient(90deg, rgba(255,255,255,0.3) 0.5px, transparent 0.5px)`,
            backgroundSize: '40px 40px',
          }}
        />
      </div>
      
      <Suspense fallback={
        <div className="w-8 h-8 border-2 border-white/10 border-t-accent rounded-full animate-spin" />
      }>
        <LoginForm />
      </Suspense>
    </div>
  )
}
