'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, Check, Eye, EyeOff, Mail, Shield, Zap, TrendingUp } 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>
  )
}

const benefits = [
  { text: 'Live Market Feed', icon: Zap },
  { text: 'Daily Scan Reports', icon: Shield },
  { text: 'Yield Intel Access', icon: TrendingUp },
]

function RegisterForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { register } = 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 [registered, setRegistered] = useState(false)

  // Get redirect URL from query params
  const redirectTo = searchParams.get('redirect') || '/terminal/hunt'
  const refFromUrl = searchParams.get('ref')

  const getCookie = (name: string): string | null => {
    if (typeof document === 'undefined') return null
    const m = document.cookie.match(new RegExp(`(?:^|; )${name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\\\$&')}=([^;]*)`))
    return m ? decodeURIComponent(m[1]) : null
  }

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

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

    try {
      const ref = refFromUrl || getCookie('pounce_ref') || undefined
      await register(email, password, undefined, ref || undefined)
      
      if (redirectTo !== '/terminal/hunt') {
        localStorage.setItem('pounce_redirect_after_login', redirectTo)
      }
      
      setRegistered(true)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Registration failed')
    } finally {
      setLoading(false)
    }
  }

  // Generate login link with redirect preserved
  const loginLink = redirectTo !== '/terminal/hunt' 
    ? `/login?redirect=${encodeURIComponent(redirectTo)}`
    : '/login'

  // Show verification message after registration
  if (registered) {
    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">
        {/* Background Atmosphere */}
        <div className="fixed inset-0 pointer-events-none">
            <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.03] mix-blend-overlay" />
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] bg-accent/[0.02] rounded-full blur-[120px]" />
        </div>
        
        <div className="relative w-full max-w-[450px] animate-fade-in z-10">
          <div className="bg-[#050505] border border-white/10 p-10 text-center relative 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" />

             <div className="w-16 h-16 bg-accent/10 border border-accent/20 flex items-center justify-center mx-auto mb-8 rounded-none">
                <Mail className="w-8 h-8 text-accent" />
             </div>
             
             <h2 className="font-display text-3xl text-white mb-4">
                Verify Credentials
             </h2>
             <p className="text-sm font-mono text-white/50 mb-8 leading-relaxed">
                Security protocol initiated. Verification link sent to <br/><strong className="text-white">{email}</strong>
             </p>
             
             <div className="space-y-4">
                <Link
                href={loginLink}
                className="block w-full py-4 bg-white text-black text-xs font-bold uppercase tracking-[0.2em] hover:bg-accent transition-all"
                style={{ clipPath: 'polygon(10px 0, 100% 0, 100% 100%, 0 100%, 0 10px)' }}
                >
                Proceed to Login
                </Link>
                <Link
                href="/verify-email"
                className="block w-full py-4 border border-white/10 text-white/40 text-xs font-bold uppercase tracking-[0.2em] hover:text-white hover:border-white/30 transition-all"
                >
                Resend Link
                </Link>
             </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex 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-[-20%] left-[-10%] w-[70vw] h-[70vw] bg-accent/5 rounded-full blur-[150px] animate-pulse-slow mix-blend-screen" />
        <div className="absolute bottom-[-20%] right-[-10%] w-[60vw] h-[60vw] bg-purple-500/5 rounded-full blur-[180px] animate-pulse-slower mix-blend-screen" />
        
        {/* Grid Overlay */}
        <div 
          className="absolute inset-0 opacity-[0.02] 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: '60px 60px',
          }}
        />
      </div>
      
      {/* Left Panel - Form */}
      <div className="flex-1 flex items-center justify-center px-4 sm:px-6 py-8 sm:py-12 relative z-10">
        <div className="relative w-full max-w-[450px] animate-fade-in">
          {/* Card Container */}
          <div className="bg-[#050505] border border-white/10 relative p-8 sm:p-10 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-10 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" />
                   New Operator
                </span>
                <h1 className="font-display text-3xl text-white mb-2 tracking-tight">
                   Initialize Access.
                </h1>
                <p className="text-xs font-mono text-white/40">
                   Create your secure terminal account.
                </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.CH"
                         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">Create Passcode</label>
                      <div className="relative">
                         <input
                            type={showPassword ? 'text' : 'password'}
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            placeholder="MIN 8 CHARS"
                            required
                            minLength={8}
                            autoComplete="new-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>

                <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" />
                   ) : (
                      <>
                         Enter Terminal
                         <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>
             )}

             {/* Login Link */}
             <div className="mt-8 pt-8 border-t border-white/10 text-center">
                <p className="text-xs font-mono text-white/40">
                   Already authorized?{' '}
                   <Link href={loginLink} className="text-white hover:text-accent border-b border-white/20 hover:border-accent transition-all pb-0.5 ml-1">
                      Sign In
                   </Link>
                </p>
             </div>
          </div>
        </div>
      </div>

      {/* Right Panel - Benefits */}
      <div className="hidden lg:flex flex-1 bg-[#030303] items-center justify-center p-8 xl:p-12 border-l border-white/10 relative overflow-hidden">
         <div className="absolute inset-0 bg-[url('/noise.png')] opacity-[0.05]" />
         <div className="max-w-md animate-slide-up delay-200 relative z-10">
            <div className="inline-flex items-center gap-2 px-3 py-1.5 bg-accent/5 border border-accent/20 mb-8 rounded-none">
               <div className="w-1.5 h-1.5 bg-accent animate-pulse" />
               <span className="text-[10px] uppercase tracking-widest text-accent font-bold">Scout Access: Granted</span>
            </div>
            
            <h2 className="font-display text-4xl leading-tight text-white mb-10">
               Your command center is waiting.
            </h2>
            
            <ul className="space-y-6">
               {benefits.map((item) => (
                  <li key={item.text} className="flex items-center gap-4 group">
                     <div className="w-10 h-10 border border-white/10 bg-white/5 flex items-center justify-center shrink-0 group-hover:border-accent/50 group-hover:text-accent transition-all">
                        <item.icon className="w-5 h-5 text-white/60 group-hover:text-accent transition-colors" strokeWidth={1.5} />
                     </div>
                     <span className="font-mono text-sm text-white/60 group-hover:text-white transition-colors">{item.text}</span>
                  </li>
               ))}
            </ul>
            
            <div className="h-px w-full bg-white/10 my-10" />
            
            <p className="font-mono text-xs text-white/30">
               // ENCRYPTED CONNECTION<br/>
               // NO CREDIT CARD REQUIRED
            </p>
         </div>
      </div>
    </div>
  )
}

export default function RegisterPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center bg-[#020202]">
        <div className="w-8 h-8 border-2 border-white/10 border-t-accent rounded-full animate-spin" />
      </div>
    }>
      <RegisterForm />
    </Suspense>
  )
}
