import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { ArrowLeft, User, Mail, Lock, Building, MapPin } from 'lucide-react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useGoogleReCaptcha } from 'react-google-recaptcha-v3';
import axios from 'axios';

export const Register = () => {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: ''
  });
  const [error, setError] = useState('');
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isLoading, setIsLoading] = useState(false);
  
  const navigate = useNavigate();
  const { registerWithEmail, loginWithGoogle, currentUser, loading } = useAuth();
  const { executeRecaptcha } = useGoogleReCaptcha();
  const location = useLocation();

  // Read URL parameters for redirect
  const searchParams = new URLSearchParams(location.search);
  const redirectParam = searchParams.get('redirect');

  useEffect(() => {
    // If the user is already logged in, redirect them immediately to their destination
    if (!loading && currentUser) {
      if (redirectParam) {
        navigate(redirectParam);
      } else {
        navigate('/client');
      }
    }
  }, [currentUser, loading, navigate, redirectParam]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    let finalValue = value;
    if (name === 'email') {
      finalValue = finalValue.trim().toLowerCase();
    }
    setFormData(prev => ({ ...prev, [name]: finalValue }));
    if (errors[name]) {
      setErrors(prev => {
        const next = { ...prev };
        delete next[name];
        return next;
      });
    }
    setError('');
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    if (!formData.firstName.trim()) newErrors.firstName = "Requis";
    if (!formData.lastName.trim()) newErrors.lastName = "Requis";
    const emailTrimmed = formData.email.trim().toLowerCase();
    if (!emailTrimmed) {
      newErrors.email = "Requis";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailTrimmed)) {
      newErrors.email = "Adresse email invalide";
    }
    if (!formData.password) newErrors.password = "Requis";
    else if (formData.password.length < 6) newErrors.password = "Min 6 caractères";
    if (formData.password !== formData.confirmPassword) newErrors.confirmPassword = "Les mots de passe ne correspondent pas";
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleGoogleLogin = async () => {
    setIsLoading(true);
    setError('');
    try {
      document.cookie = "allow_google_signup=1; path=/; max-age=300";
      await loginWithGoogle(redirectParam || '/client');
      import('react-ga4').then(ReactGA => {
        if (ReactGA.default.isInitialized) {
          ReactGA.default.event({
            category: 'User',
            action: 'Sign Up',
            label: 'Google'
          });
        }
      });
      // Navigation is handled by AuthContext loginWithGoogle callback wrapper, 
      // but if it wasn't, we would navigate here. Since we have the useEffect, it will auto-navigate when currentUser changes.
    } catch (err: any) {
      console.error(err);
      if (err.code === 'auth/popup-closed-by-user') {
        setError('La fenêtre de connexion a été fermée.');
      } else {
        setError(err.message || 'Erreur lors de l\'inscription avec Google.');
      }
      setIsLoading(false);
    }
  };

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;
    
    setError('');
    setIsLoading(true);

    try {
      let token = "dummy_token";
      
      if (process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY) {
        if (!executeRecaptcha) {
          setError("Le système anti-spam n'est pas encore prêt. Veuillez patienter.");
          setIsLoading(false);
          return;
        }
        token = await executeRecaptcha('register');
      }

      const recaptchaRes = await axios.post('/api/recaptcha', { token });
      if (!recaptchaRes.data.success) {
        setError("La vérification anti-spam a échoué.");
        setIsLoading(false);
        return;
      }

      // Prepare profile data
      const profileData = {
        firstName: formData.firstName,
        lastName: formData.lastName,
        phone: formData.phone
      };

      await registerWithEmail(formData.email, formData.password, profileData);
      
      import('react-ga4').then(ReactGA => {
        if (ReactGA.default.isInitialized) {
          ReactGA.default.event({
            category: 'User',
            action: 'Sign Up',
            label: 'Email'
          });
        }
      });
      
      // Successfully registered. Navigate to the requested redirect or client dashboard.
      if (redirectParam) {
        navigate(redirectParam);
      } else {
        navigate('/client');
      }

    } catch (err: any) {
      console.error(err);
      const errorMessage = err.response?.data?.error || err.message || err.code;
      if (errorMessage === 'auth/email-already-in-use') {
        setError("Cet email est déjà utilisé. Veuillez vous connecter.");
      } else {
        setError("Erreur lors de l'inscription. Veuillez réessayer.");
      }
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#fafbfc] dark:bg-slate-950 flex flex-col justify-center py-12 sm:px-6 lg:px-8 relative overflow-hidden transition-colors duration-500">
      {/* Background decorations */}
      <div className="absolute top-0 right-0 -translate-y-12 translate-x-1/3">
        <div className="w-96 h-96 bg-blue-400/20 dark:bg-blue-600/10 rounded-full blur-3xl" />
      </div>
      <div className="absolute bottom-0 left-0 translate-y-1/3 -translate-x-1/3">
        <div className="w-96 h-96 bg-purple-400/20 dark:bg-purple-600/10 rounded-full blur-3xl" />
      </div>

      <div className="sm:mx-auto sm:w-full sm:max-w-md relative z-10">
        <h2 className="text-center text-3xl font-black tracking-tight text-slate-900 dark:text-white flex items-center justify-center gap-3">
          <Link to="/" className="font-bold text-blue-600 hover:text-blue-500 transition-colors" aria-label="Retour à l'accueil">
            <ArrowLeft />
          </Link>
          Créer votre compte
        </h2>
      </div>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-[500px] relative z-10">
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-white dark:bg-slate-900 py-10 px-6 shadow-2xl shadow-slate-200/50 dark:shadow-none sm:rounded-[2.5rem] sm:px-12 border border-slate-100 dark:border-slate-800"
        >
          <div className="mb-8">
            <button
              type="button"
              onClick={handleGoogleLogin}
              disabled={isLoading}
              className="w-full flex justify-center items-center gap-3 py-4 px-4 border-2 border-slate-100 dark:border-slate-800 rounded-2xl text-lg font-black text-slate-900 dark:text-white bg-white dark:bg-slate-900 hover:bg-slate-50 dark:hover:bg-slate-800 transition-all active:scale-[0.98] disabled:opacity-70 group"
            >
              <img src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg" alt="Google" className="w-6 h-6" />
              <span>S'inscrire avec Google</span>
            </button>
            <div className="relative my-8">
              <div className="absolute inset-0 flex items-center">
                <div className="w-full border-t border-slate-100 dark:border-slate-800"></div>
              </div>
              <div className="relative flex justify-center text-sm uppercase">
                <span className="bg-white dark:bg-slate-900 px-4 text-[10px] font-black text-slate-400 tracking-widest leading-none">Ou par email</span>
              </div>
            </div>
          </div>

          <form className="space-y-6" onSubmit={handleRegister}>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <label className="text-[10px] font-bold text-slate-400 uppercase tracking-[0.2em] pl-1">
                  Prénom <span className="text-red-500">*</span>
                </label>
                <div className="relative group">
                  <User className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-300 group-focus-within:text-blue-500 transition-colors" />
                  <input
                    name="firstName"
                    value={formData.firstName}
                    onChange={handleChange}
                    disabled={isLoading}
                    className="w-full bg-slate-50 dark:bg-slate-800 border-2 rounded-2xl pl-12 pr-4 py-3 focus:outline-none transition-all font-medium text-slate-900 dark:text-white border-slate-100 dark:border-slate-700 focus:border-blue-500 disabled:opacity-50"
                  />
                </div>
                {errors.firstName && <p className="text-[10px] text-red-500 font-bold pl-1 italic">{errors.firstName}</p>}
              </div>
              
              <div className="space-y-2">
                <label className="text-[10px] font-bold text-slate-400 uppercase tracking-[0.2em] pl-1">
                  Nom <span className="text-red-500">*</span>
                </label>
                <div className="relative group">
                  <User className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-300 group-focus-within:text-blue-500 transition-colors" />
                  <input
                    name="lastName"
                    value={formData.lastName}
                    onChange={handleChange}
                    disabled={isLoading}
                    className="w-full bg-slate-50 dark:bg-slate-800 border-2 rounded-2xl pl-12 pr-4 py-3 focus:outline-none transition-all font-medium text-slate-900 dark:text-white border-slate-100 dark:border-slate-700 focus:border-blue-500 disabled:opacity-50"
                  />
                </div>
                {errors.lastName && <p className="text-[10px] text-red-500 font-bold pl-1 italic">{errors.lastName}</p>}
              </div>
            </div>

            <div className="space-y-2">
              <label className="text-[10px] font-bold text-slate-400 uppercase tracking-[0.2em] pl-1">
                Adresse Email <span className="text-red-500">*</span>
              </label>
              <div className="relative group">
                <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-300 group-focus-within:text-blue-500 transition-colors" />
                <input
                  name="email"
                  type="email"
                  value={formData.email}
                  onChange={handleChange}
                  disabled={isLoading}
                  className="w-full bg-slate-50 dark:bg-slate-800 border-2 rounded-2xl pl-12 pr-4 py-3 focus:outline-none transition-all font-medium text-slate-900 dark:text-white border-slate-100 dark:border-slate-700 focus:border-blue-500 disabled:opacity-50"
                  autoComplete="email"
                />
              </div>
              {errors.email && <p className="text-[10px] text-red-500 font-bold pl-1 italic">{errors.email}</p>}
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <label className="text-[10px] font-bold text-slate-400 uppercase tracking-[0.2em] pl-1">
                  Mot de passe <span className="text-red-500">*</span>
                </label>
                <div className="relative group">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-300 group-focus-within:text-blue-500 transition-colors" />
                  <input
                    name="password"
                    type="password"
                    value={formData.password}
                    onChange={handleChange}
                    disabled={isLoading}
                    className="w-full bg-slate-50 dark:bg-slate-800 border-2 rounded-2xl pl-12 pr-4 py-3 focus:outline-none transition-all font-medium text-slate-900 dark:text-white border-slate-100 dark:border-slate-700 focus:border-blue-500 disabled:opacity-50"
                  />
                </div>
                {errors.password && <p className="text-[10px] text-red-500 font-bold pl-1 italic">{errors.password}</p>}
              </div>

              <div className="space-y-2">
                <label className="text-[10px] font-bold text-slate-400 uppercase tracking-[0.2em] pl-1">
                  Confirmer <span className="text-red-500">*</span>
                </label>
                <div className="relative group">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-300 group-focus-within:text-blue-500 transition-colors" />
                  <input
                    name="confirmPassword"
                    type="password"
                    value={formData.confirmPassword}
                    onChange={handleChange}
                    disabled={isLoading}
                    className="w-full bg-slate-50 dark:bg-slate-800 border-2 rounded-2xl pl-12 pr-4 py-3 focus:outline-none transition-all font-medium text-slate-900 dark:text-white border-slate-100 dark:border-slate-700 focus:border-blue-500 disabled:opacity-50"
                  />
                </div>
                {errors.confirmPassword && <p className="text-[10px] text-red-500 font-bold pl-1 italic">{errors.confirmPassword}</p>}
              </div>
            </div>

            {error && (
              <div className="bg-red-50 dark:bg-red-900/30 text-red-600 dark:text-red-400 p-4 rounded-2xl text-sm font-bold text-center border border-red-100 dark:border-red-800">
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={isLoading}
              className="w-full flex justify-center py-4 px-4 border border-transparent rounded-2xl shadow-xl shadow-blue-500/20 text-lg font-black text-white bg-blue-600 hover:bg-blue-700 focus:outline-none transition-all active:scale-[0.98] disabled:opacity-70 disabled:active:scale-100"
            >
              {isLoading ? (
                <div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              ) : (
                "Créer mon compte"
              )}
            </button>
          </form>
          
          <div className="mt-8 text-center">
            <p className="text-sm font-medium text-slate-500 dark:text-slate-400">
              Déjà un compte ?{' '}
              <Link to={redirectParam ? `/login?redirect=${encodeURIComponent(redirectParam)}` : '/login'} className="font-bold text-blue-600 hover:text-blue-500 transition-colors">
                Connectez-vous
              </Link>
            </p>
          </div>
        </motion.div>
      </div>
    </div>
  );
};
