import { useState, useEffect } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { useAuth } from '@/context/AuthContext'
import { analytics } from '@/hooks/useAnalytics'
import { captureUTMParams } from '@/lib/analytics'
import { api } from '@/lib/api'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Mail, Lock, User, ArrowRight, AlertCircle, Check, Sparkles } from 'lucide-react'

export function Register() {
  const [searchParams] = useSearchParams()
  const selectedPlan = searchParams.get('plan') || 'pro'
  const referralCode = searchParams.get('ref') || null
  
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  
  const { register, user } = useAuth()
  const navigate = useNavigate()

  // Capture UTM parameters on mount
  useEffect(() => {
    captureUTMParams()
  }, [])

  // Track referral and signup after user is registered
  useEffect(() => {
    if (user?.$id && referralCode) {
      // Track referral if code exists
      api.trackReferral(referralCode).catch((err) => {
        console.error('Failed to track referral:', err)
      })
    }
    
    if (user?.$id) {
      // Track signup conversion with UTM parameters
      analytics.trackSignup(user.$id, email)
      analytics.setUserId(user.$id)
    }
  }, [user, referralCode, email])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')

    if (password !== confirmPassword) {
      setError('Passwords do not match.')
      return
    }

    if (password.length < 8) {
      setError('Password must be at least 8 characters long.')
      return
    }

    setLoading(true)

    try {
      await register(email, password, name)
      navigate('/setup')
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Registration failed. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex">
      {/* Left side - Decorative */}
      <div className="hidden lg:flex lg:flex-1 bg-gradient-to-br from-slate-900 via-primary-900 to-slate-900 items-center justify-center p-12 relative overflow-hidden">
        {/* Background pattern */}
        <div className="absolute inset-0 gradient-mesh opacity-20" />
        
        <div className="relative max-w-md">
          <Badge className="mb-6 bg-accent-500/20 text-accent-300 border-accent-400/30">
            <Sparkles className="w-3 h-3 mr-1" />
            14-day free trial
          </Badge>
          
          <h2 className="text-4xl font-bold text-white mb-6">
            Start with MailFlow today
          </h2>
          
          <ul className="space-y-4 mb-8">
            {[
              'No credit card required',
              'Gmail & Outlook support',
              'AI-powered categorization',
              'Cancel anytime',
            ].map((item, index) => (
              <li key={index} className="flex items-center gap-3 text-slate-300">
                <div className="w-6 h-6 rounded-full bg-accent-500/20 flex items-center justify-center">
                  <Check className="w-4 h-4 text-accent-400" />
                </div>
                {item}
              </li>
            ))}
          </ul>

          {/* Plan indicator */}
          <div className="bg-white/10 backdrop-blur rounded-xl p-4 border border-white/10">
            <p className="text-sm text-slate-400 mb-1">Selected plan</p>
            <p className="text-xl font-semibold text-white capitalize">{selectedPlan}</p>
          </div>
        </div>
      </div>

      {/* Right side - Form */}
      <div className="flex-1 flex items-center justify-center px-4 sm:px-6 lg:px-8 bg-white dark:bg-slate-900">
        <div className="w-full max-w-md">
          {/* Logo */}
          <Link to="/" className="flex items-center mb-8 leading-none">
            <img 
              src="/logo.png" 
              alt="MailFlow Logo" 
              className="w-24 h-24 rounded-xl object-contain pr-[5px] block"
              style={{ display: 'block', margin: 0, padding: 0 }}
            />
            <span className="text-xl font-bold text-slate-900 dark:text-slate-100 ml-[5px]">
              Mail<span className="text-primary-600 dark:text-primary-400">Flow</span>
            </span>
          </Link>

          <h1 className="text-3xl font-bold text-slate-900 dark:text-slate-100 mb-2">
            Create account
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mb-8">
            Ready to go in less than a minute.
          </p>

          {/* Error message */}
          {error && (
            <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-xl flex items-start gap-3">
              <AlertCircle className="w-5 h-5 text-red-500 dark:text-red-400 flex-shrink-0 mt-0.5" />
              <p className="text-sm text-red-600 dark:text-red-300">{error}</p>
            </div>
          )}

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-5">
            <div className="space-y-2">
              <Label htmlFor="name">Name (optional)</Label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <Input
                  id="name"
                  type="text"
                  placeholder="John Smith"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="email">Email address</Label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <Input
                  id="email"
                  type="email"
                  placeholder="john@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="pl-10"
                  required
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Password</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <Input
                  id="password"
                  type="password"
                  placeholder="At least 8 characters"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="pl-10"
                  required
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="confirmPassword">Confirm password</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <Input
                  id="confirmPassword"
                  type="password"
                  placeholder="Repeat password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="pl-10"
                  required
                />
              </div>
            </div>

            <Button type="submit" className="w-full" size="lg" disabled={loading}>
              {loading ? (
                <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              ) : (
                <>
                  Get started free
                  <ArrowRight className="w-5 h-5 ml-2" />
                </>
              )}
            </Button>

            <p className="text-xs text-slate-500 dark:text-slate-400 text-center">
              By signing up, you agree to our{' '}
              <a href="#" className="text-primary-600 dark:text-primary-400 hover:underline">Terms of Service</a> and{' '}
              <a href="#" className="text-primary-600 dark:text-primary-400 hover:underline">Privacy Policy</a>.
            </p>
          </form>

          <p className="mt-8 text-center text-slate-600 dark:text-slate-400">
            Already have an account?{' '}
            <Link to="/login" className="text-primary-600 dark:text-primary-400 font-semibold hover:text-primary-700 dark:hover:text-primary-300">
              Sign in
            </Link>
          </p>
        </div>
      </div>
    </div>
  )
}
