'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 } 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>
  )
}

const benefits = [
  'Track up to 5 domains. Free.',
  'Daily scans. You never miss a drop.',
  'Instant alerts. Know first.',
  'Expiry intel. Plan your move.',
]

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') || '/command/dashboard'

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

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

    try {
      await register(email, password)
      
      // Store redirect URL for after email verification
      // This will be picked up by the login page after verification
      if (redirectTo !== '/command/dashboard') {
        localStorage.setItem('pounce_redirect_after_login', redirectTo)
      }
      
      // Show verification message
      setRegistered(true)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Registration failed')
    } finally {
      setLoading(false)
    }
  }

  // Generate login link with redirect preserved
  const loginLink = redirectTo !== '/command/dashboard' 
    ? `/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">
        <div className="fixed inset-0 pointer-events-none">
          <div className="absolute top-1/4 left-1/3 w-[400px] h-[300px] bg-accent/[0.02] rounded-full blur-3xl" />
        </div>
        
        <div className="relative w-full max-w-md text-center animate-fade-in">
          <div className="w-20 h-20 bg-accent/10 rounded-full flex items-center justify-center mx-auto mb-6">
            <Mail className="w-10 h-10 text-accent" />
          </div>
          <h2 className="font-display text-3xl sm:text-4xl text-foreground mb-4">
            Check your inbox
          </h2>
          <p className="text-lg text-foreground-muted mb-6">
            We&apos;ve sent a verification link to <strong className="text-foreground">{email}</strong>
          </p>
          <p className="text-sm text-foreground-subtle mb-8">
            Click the link in the email to verify your account and start hunting domains.
          </p>
          <div className="space-y-3">
            <Link
              href={loginLink}
              className="block w-full py-3 bg-foreground text-background text-sm font-medium rounded-xl hover:bg-foreground/90 transition-all"
            >
              Go to Login
            </Link>
            <Link
              href="/verify-email"
              className="block w-full py-3 border border-border text-foreground-muted text-sm font-medium rounded-xl hover:border-foreground/20 transition-all"
            >
              Resend Verification Email
            </Link>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex relative">
      {/* Ambient glow */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-1/4 left-1/3 w-[400px] h-[300px] bg-accent/[0.02] rounded-full blur-3xl" />
      </div>
      
      {/* Left Panel - Form */}
      <div className="flex-1 flex items-center justify-center px-4 sm:px-6 py-8 sm:py-12">
        <div className="relative w-full max-w-sm animate-fade-in">
          {/* Logo */}
          <Link href="/" className="block mb-12 sm:mb-16 hover:opacity-80 transition-opacity duration-300">
            <Logo />
          </Link>

          {/* Header */}
          <div className="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">
              Join the hunt.
            </h1>
            <p className="text-body-sm sm:text-body text-foreground-muted">
              Start tracking domains in under a minute
            </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">{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="Create password (min. 8 characters)"
                  required
                  minLength={8}
                  autoComplete="new-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>

            <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" />
              ) : (
                <>
                  Start Hunting
                  <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" />
                    Sign up 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" />
                    Sign up with GitHub
                  </a>
                )}
              </div>
            </div>
          )}

          {/* Login Link */}
          <p className="mt-8 sm:mt-10 text-body-xs sm:text-body-sm text-foreground-muted">
            Already have an account?{' '}
            <Link href={loginLink} className="text-foreground hover:text-accent transition-colors duration-300">
              Sign in
            </Link>
          </p>
        </div>
      </div>

      {/* Right Panel - Benefits */}
      <div className="hidden lg:flex flex-1 bg-background-secondary/50 items-center justify-center p-8 xl:p-12 border-l border-border-subtle">
        <div className="max-w-sm animate-slide-up delay-200">
          <div className="inline-flex items-center gap-2 sm:gap-2.5 px-3 sm:px-4 py-1.5 sm:py-2 bg-background-tertiary border border-border rounded-full mb-8 sm:mb-10">
            <div className="w-1.5 h-1.5 rounded-full bg-accent" />
            <span className="text-ui-sm sm:text-ui text-foreground-muted">Free Forever</span>
          </div>
          
          <h2 className="font-display text-[1.75rem] sm:text-[2.25rem] md:text-[2.75rem] leading-[1.15] tracking-[-0.025em] text-foreground mb-8 sm:mb-10">
            Your hunting gear. Ready to go.
          </h2>
          
          <ul className="space-y-4 sm:space-y-5">
            {benefits.map((item) => (
              <li key={item} className="flex items-center gap-3 sm:gap-4">
                <div className="w-8 sm:w-9 h-8 sm:h-9 rounded-lg bg-accent/10 flex items-center justify-center shrink-0">
                  <Check className="w-3.5 sm:w-4 h-3.5 sm:h-4 text-accent" strokeWidth={2.5} />
                </div>
                <span className="text-body-sm sm:text-body text-foreground-muted">{item}</span>
              </li>
            ))}
          </ul>
          
          <div className="divider my-8 sm:my-10" />
          
          <p className="text-body-xs sm:text-body-sm text-foreground-subtle">
            No credit card required. Upgrade anytime.
          </p>
        </div>
      </div>
    </div>
  )
}

export default function RegisterPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex items-center justify-center">
        <div className="w-5 h-5 border-2 border-accent border-t-transparent rounded-full animate-spin" />
      </div>
    }>
      <RegisterForm />
    </Suspense>
  )
}
