import { useState } from 'react'
import { Link, useNavigate } from 'react-router'
import { motion } from 'framer-motion'
import { Mail, Lock, User, Eye, EyeOff } from 'lucide-react'
import { register as apiRegister } from '../api/auth'
import { useAuth } from '../context/AuthContext'
import { Button } from '../components/ui/Button'
import { showToast } from '../utils/toast'

export function RegisterPage() {
  const [formData, setFormData] = useState({
    display_name: '',
    email: '',
    password: '',
    confirmPassword: ''
  })
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})
  
  const { login } = useAuth()
  const navigate = useNavigate()

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {}

    // Name validation
    if (!formData.display_name.trim()) {
      newErrors.display_name = 'Name ist erforderlich'
    } else if (formData.display_name.trim().length < 2) {
      newErrors.display_name = 'Name muss mindestens 2 Zeichen lang sein'
    }

    // Email validation
    if (!formData.email) {
      newErrors.email = 'E-Mail ist erforderlich'
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Ungültige E-Mail-Adresse'
    }

    // Password validation
    if (!formData.password) {
      newErrors.password = 'Passwort ist erforderlich'
    } else if (formData.password.length < 6) {
      newErrors.password = 'Passwort muss mindestens 6 Zeichen lang sein'
    }

    // Confirm password validation
    if (!formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwort bestätigen ist erforderlich'
    } else if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwörter stimmen nicht überein'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleChange = (field: keyof typeof formData) => (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setFormData({ ...formData, [field]: e.target.value })
    // Clear error for this field when user starts typing
    if (errors[field]) {
      setErrors({ ...errors, [field]: '' })
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!validateForm()) {
      return
    }

    setIsLoading(true)
    setErrors({})

    try {
      const response = await apiRegister({
        display_name: formData.display_name.trim(),
        email: formData.email,
        password: formData.password
      })
      login(response.access_token, response.user)
      showToast.success(`Willkommen bei Luna Rezepte, ${response.user.display_name}!`)
      navigate('/', { replace: true })
    } catch (err: any) {
      if (err.message?.includes('409')) {
        setErrors({ email: 'E-Mail-Adresse ist bereits registriert' })
        showToast.error('E-Mail bereits registriert')
      } else {
        setErrors({ general: 'Registrierung fehlgeschlagen. Bitte versuche es erneut.' })
        showToast.error('Registrierung fehlgeschlagen')
      }
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <motion.div
        className="w-full max-w-md"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
      >
        {/* Header */}
        <div className="text-center mb-8">
          <motion.div
            className="text-6xl mb-4"
            initial={{ scale: 0.8 }}
            animate={{ scale: 1 }}
          >
            👨‍🍳
          </motion.div>
          <h1 className="font-display text-3xl text-espresso mb-2">
            Account erstellen
          </h1>
          <p className="text-warm-grey">
            Registriere dich und starte deine Rezeptsammlung
          </p>
        </div>

        {/* Registration Form */}
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Name Field */}
          <div>
            <label htmlFor="name" className="block text-sm font-medium text-espresso mb-2">
              Name
            </label>
            <div className="relative">
              <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-warm-grey" size={18} />
              <input
                id="name"
                type="text"
                value={formData.display_name}
                onChange={handleChange('display_name')}
                className={`w-full pl-10 pr-4 py-3 rounded-xl border ${errors.display_name ? 'border-berry-red' : 'border-sand'} focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors`}
                placeholder="Dein Name"
              />
            </div>
            {errors.display_name && (
              <p className="text-berry-red text-sm mt-1">{errors.display_name}</p>
            )}
          </div>

          {/* Email Field */}
          <div>
            <label htmlFor="email" className="block text-sm font-medium text-espresso mb-2">
              E-Mail
            </label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-warm-grey" size={18} />
              <input
                id="email"
                type="email"
                value={formData.email}
                onChange={handleChange('email')}
                className={`w-full pl-10 pr-4 py-3 rounded-xl border ${errors.email ? 'border-berry-red' : 'border-sand'} focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors`}
                placeholder="deine@email.de"
              />
            </div>
            {errors.email && (
              <p className="text-berry-red text-sm mt-1">{errors.email}</p>
            )}
          </div>

          {/* Password Field */}
          <div>
            <label htmlFor="password" className="block text-sm font-medium text-espresso mb-2">
              Passwort
            </label>
            <div className="relative">
              <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-warm-grey" size={18} />
              <input
                id="password"
                type={showPassword ? 'text' : 'password'}
                value={formData.password}
                onChange={handleChange('password')}
                className={`w-full pl-10 pr-12 py-3 rounded-xl border ${errors.password ? 'border-berry-red' : 'border-sand'} focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors`}
                placeholder="••••••••"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-warm-grey hover:text-espresso transition-colors"
              >
                {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
              </button>
            </div>
            {errors.password && (
              <p className="text-berry-red text-sm mt-1">{errors.password}</p>
            )}
          </div>

          {/* Confirm Password Field */}
          <div>
            <label htmlFor="confirmPassword" className="block text-sm font-medium text-espresso mb-2">
              Passwort bestätigen
            </label>
            <div className="relative">
              <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-warm-grey" size={18} />
              <input
                id="confirmPassword"
                type={showConfirmPassword ? 'text' : 'password'}
                value={formData.confirmPassword}
                onChange={handleChange('confirmPassword')}
                className={`w-full pl-10 pr-12 py-3 rounded-xl border ${errors.confirmPassword ? 'border-berry-red' : 'border-sand'} focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none transition-colors`}
                placeholder="••••••••"
              />
              <button
                type="button"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute right-3 top-1/2 transform -translate-y-1/2 text-warm-grey hover:text-espresso transition-colors"
              >
                {showConfirmPassword ? <EyeOff size={18} /> : <Eye size={18} />}
              </button>
            </div>
            {errors.confirmPassword && (
              <p className="text-berry-red text-sm mt-1">{errors.confirmPassword}</p>
            )}
          </div>

          {/* General Error Message */}
          {errors.general && (
            <motion.div
              className="text-berry-red text-sm text-center"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
            >
              {errors.general}
            </motion.div>
          )}

          {/* Submit Button */}
          <Button
            type="submit"
            disabled={isLoading}
            className="w-full min-h-[44px] py-3"
          >
            {isLoading ? 'Account wird erstellt...' : 'Registrieren'}
          </Button>
        </form>

        {/* Login Link */}
        <div className="text-center mt-6">
          <p className="text-warm-grey">
            Schon einen Account?{' '}
            <Link to="/login" className="text-primary hover:underline font-medium">
              Jetzt anmelden
            </Link>
          </p>
        </div>
      </motion.div>
    </div>
  )
}