"use client";
import { useState, useRef } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useAuth } from "@/contexts/AuthContext";
import { registerSchema, RegisterFormData } from "@/lib/validations";
import Link from "next/link";
import TeaIconsBackground from "@/components/TeaIconsBackground";
import { ROUTES, API_BASE_URL, API_ENDPOINTS } from "@/utils/constants";
import { isValidEmail } from "@/utils/helpers";
import ReCAPTCHA from "react-google-recaptcha";

export default function RegisterPage() {
  const { register: registerUser } = useAuth();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [animationKey] = useState(Date.now());
  const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const [captchaError, setCaptchaError] = useState(false);
  const recaptchaRef = useRef<ReCAPTCHA>(null);

  // Email validation state
  const [emailStatus, setEmailStatus] = useState<{
    checking: boolean;
    exists: boolean | null;
    valid: boolean | null;
    message: string;
  }>({ checking: false, exists: null, valid: null, message: '' });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema),
  });

  const onCaptchaChange = (token: string | null) => {
    setCaptchaToken(token);
    setCaptchaError(false);
  };

  // Vérifier si l'email existe déjà
  const checkEmail = async (email: string) => {
    if (!email || !isValidEmail(email)) {
      setEmailStatus({ checking: false, exists: null, valid: null, message: '' });
      return;
    }

    setEmailStatus({ checking: true, exists: null, valid: null, message: 'Vérification...' });

    try {
      const response = await fetch(`${API_BASE_URL}${API_ENDPOINTS.AUTH.CHECK_EMAIL}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });

      const data = await response.json();

      setEmailStatus({
        checking: false,
        exists: data.exists,
        valid: data.isValid,
        message: data.message,
      });
    } catch (error) {
      console.error('Error checking email:', error);
      setEmailStatus({ checking: false, exists: null, valid: null, message: '' });
    }
  };

  const onSubmit = async (data: RegisterFormData) => {
    // Vérifier si l'email existe déjà
    if (emailStatus.exists) {
      return;
    }

    // Vérifier le captcha
    if (!captchaToken) {
      setCaptchaError(true);
      return;
    }

    setIsSubmitting(true);
    try {
      await registerUser({ ...data, captchaToken });
    } catch (error) {
      console.error("Registration error:", error);
      // Reset captcha en cas d'erreur
      recaptchaRef.current?.reset();
      setCaptchaToken(null);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen relative flex items-center justify-center py-12 px-4">
      <TeaIconsBackground animationKey={animationKey} />

      <div className="w-full max-w-md relative z-10">

        {/* Title */}
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-gray-900 mb-2">Inscription</h1>
          <p className="text-gray-600">
            Créez un compte pour participer au jeu-concours
          </p>
        </div>

        {/* Main Card */}
        <div className="bg-white rounded-xl shadow-md overflow-hidden">

          {/* Tabs */}
          <div className="flex border-b border-gray-200">
            <Link
              href={ROUTES.LOGIN}
              className="flex-1 py-4 px-6 text-center font-semibold text-gray-500 bg-gray-50 hover:bg-gradient-to-r hover:from-primary-50 hover:to-primary-100 hover:text-primary-600 transition-all duration-300 hover:shadow-inner"
            >
              Connexion
            </Link>
            <button className="flex-1 py-4 px-6 text-center font-bold text-gray-900 bg-white border-b-3 border-primary-500 shadow-[0_3px_8px_rgba(11,96,41,0.2)] relative">
              <span className="relative z-10">Inscription</span>
              <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-gradient-to-r from-transparent via-primary-500 to-transparent"></div>
            </button>
          </div>

          {/* Form Container */}
          <div className="p-8">
            {/* Hidden h2 for accessibility - maintains heading hierarchy */}
            <h2 className="sr-only">Formulaire d'inscription</h2>

            {/* Registration Form */}
            <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">

              {/* Prénom et Nom */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="firstName" className="block text-sm font-semibold text-gray-900 mb-2">
                    Prénom <span className="text-red-700 font-bold" aria-hidden="true">*</span>
                    <span className="sr-only">(obligatoire)</span>
                  </label>
                  <input
                    id="firstName"
                    type="text"
                    placeholder="prénom"
                    {...register("firstName")}
                    className={`w-full px-4 py-3 border ${errors.firstName ? 'border-red-500' : 'border-gray-300'} rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent`}
                  />
                  {errors.firstName && (
                    <p className="mt-1 text-sm text-red-500">{errors.firstName.message}</p>
                  )}
                </div>

                <div>
                  <label htmlFor="lastName" className="block text-sm font-semibold text-gray-900 mb-2">
                    Nom <span className="text-red-700 font-bold" aria-hidden="true">*</span>
                    <span className="sr-only">(obligatoire)</span>
                  </label>
                  <input
                    id="lastName"
                    type="text"
                    placeholder="nom"
                    {...register("lastName")}
                    className={`w-full px-4 py-3 border ${errors.lastName ? 'border-red-500' : 'border-gray-300'} rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent`}
                  />
                  {errors.lastName && (
                    <p className="mt-1 text-sm text-red-500">{errors.lastName.message}</p>
                  )}
                </div>
              </div>

              {/* Email */}
              <div>
                <label htmlFor="email" className="block text-sm font-semibold text-gray-900 mb-2">
                  Email <span className="text-red-700 font-bold" aria-hidden="true">*</span>
                  <span className="sr-only">(obligatoire)</span>
                </label>
                <div className="relative">
                  <input
                    id="email"
                    type="email"
                    placeholder="email"
                    {...register("email")}
                    onBlur={(e) => checkEmail(e.target.value)}
                    className={`w-full px-4 py-3 border ${
                      errors.email || emailStatus.exists
                        ? 'border-red-500'
                        : emailStatus.valid
                          ? 'border-primary-500'
                          : 'border-gray-300'
                    } rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent pr-10`}
                  />
                  {/* Status icon */}
                  {emailStatus.checking && (
                    <div className="absolute right-3 top-1/2 -translate-y-1/2">
                      <svg className="animate-spin h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                    </div>
                  )}
                  {!emailStatus.checking && emailStatus.valid && (
                    <div className="absolute right-3 top-1/2 -translate-y-1/2">
                      <svg className="h-5 w-5 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                    </div>
                  )}
                  {!emailStatus.checking && emailStatus.exists && (
                    <div className="absolute right-3 top-1/2 -translate-y-1/2">
                      <svg className="h-5 w-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </div>
                  )}
                </div>
                {errors.email && (
                  <p className="mt-1 text-sm text-red-500">{errors.email.message}</p>
                )}
                {!errors.email && emailStatus.message && (
                  <p className={`mt-1 text-sm ${emailStatus.exists ? 'text-red-500' : emailStatus.valid ? 'text-primary-600' : 'text-gray-500'}`}>
                    {emailStatus.message}
                  </p>
                )}
              </div>

              {/* Téléphone */}
              <div>
                <label htmlFor="phone" className="block text-sm font-semibold text-gray-900 mb-2">
                  Téléphone <span className="sr-only">(optionnel)</span>
                </label>
                <input
                  id="phone"
                  type="tel"
                  placeholder="téléphone"
                  {...register("phone")}
                  className={`w-full px-4 py-3 border ${errors.phone ? 'border-red-500' : 'border-gray-300'} rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent`}
                />
                <p className="mt-1 text-xs text-gray-600">Optionnel - Format: 06 12 34 56 78</p>
                {errors.phone && (
                  <p className="mt-1 text-sm text-red-500">{errors.phone.message}</p>
                )}
              </div>

              {/* Mot de passe */}
              <div>
                <label htmlFor="password" className="block text-sm font-semibold text-gray-900 mb-2">
                  Mot de passe <span className="text-red-700 font-bold" aria-hidden="true">*</span>
                  <span className="sr-only">(obligatoire)</span>
                </label>
                <div className="relative">
                  <input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="mot de passe"
                    {...register("password")}
                    className={`w-full px-4 py-3 border ${errors.password ? 'border-red-500' : 'border-gray-300'} rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent pr-12`}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                    aria-label={showPassword ? "Masquer le mot de passe" : "Afficher le mot de passe"}
                  >
                    {showPassword ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                </div>
                <p className="mt-1 text-xs text-gray-600">Min. 8 caractères, 1 majuscule, 1 minuscule, 1 chiffre</p>
                {errors.password && (
                  <p className="mt-1 text-sm text-red-500">{errors.password.message}</p>
                )}
              </div>

              {/* Confirmer mot de passe */}
              <div>
                <label htmlFor="confirmPassword" className="block text-sm font-semibold text-gray-900 mb-2">
                  Confirmer le mot de passe <span className="text-red-700 font-bold" aria-hidden="true">*</span>
                  <span className="sr-only">(obligatoire)</span>
                </label>
                <div className="relative">
                  <input
                    id="confirmPassword"
                    type={showConfirmPassword ? "text" : "password"}
                    placeholder="confirmer mot de passe"
                    {...register("confirmPassword")}
                    className={`w-full px-4 py-3 border ${errors.confirmPassword ? 'border-red-500' : 'border-gray-300'} rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent pr-12`}
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                    aria-label={showConfirmPassword ? "Masquer la confirmation du mot de passe" : "Afficher la confirmation du mot de passe"}
                  >
                    {showConfirmPassword ? (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                      </svg>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                </div>
                {errors.confirmPassword && (
                  <p className="mt-1 text-sm text-red-500">{errors.confirmPassword.message}</p>
                )}
              </div>

              {/* Checkbox CGU */}
              <div className="flex items-start gap-3">
                <input
                  id="terms"
                  type="checkbox"
                  required
                  className="mt-1 w-5 h-5 text-primary-500 border-gray-300 rounded focus:ring-2 focus:ring-primary-500"
                />
                <label htmlFor="terms" className="text-sm text-gray-700 select-none cursor-pointer">
                  J'accepte les{' '}
                  <Link href="/terms" className="text-beige-800 underline hover:text-primary-500">
                    conditions d'utilisation
                  </Link>{' '}
                  et la{' '}
                  <Link href="/privacy" className="text-beige-800 underline hover:text-primary-500">
                    politique de confidentialité
                  </Link>{' '}
                  <span className="text-red-700 font-bold" aria-hidden="true">*</span>
                </label>
              </div>

              {/* reCAPTCHA */}
              <div className="flex flex-col items-center">
                <ReCAPTCHA
                  ref={recaptchaRef}
                  sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || ""}
                  onChange={onCaptchaChange}
                  onExpired={() => setCaptchaToken(null)}
                />
                {captchaError && (
                  <p className="mt-2 text-sm text-red-500">Veuillez confirmer que vous n'êtes pas un robot</p>
                )}
              </div>

              {/* Submit Button */}
              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-400 hover:to-primary-500 disabled:bg-gray-400 disabled:from-gray-400 disabled:to-gray-400 text-white font-bold px-8 py-4 rounded-lg transition-all duration-300 hover:shadow-[0_0_25px_rgba(11,96,41,0.5)] hover:scale-[1.02] shadow-lg transform"
              >
                {isSubmitting ? "Inscription..." : "S'inscrire"}
              </button>
            </form>

          </div>
        </div>
      </div>
    </div>
  );
}
