"use client";

import React, { useState, useEffect } from "react";
import "./Register.css";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useAppDispatch } from "../../../hooks/useDispatch";
import {
  registerUser,
  checkEmail,
  checkPhone,
  loginUser, // Import loginUser service
} from "../../../redux/services/auth/authServices";
import { fetchUserWallets } from "../../../redux/services/main/campaigns/mycampaign";
import { CommuneSuggestion } from "@/app/types/interfaces";
import { VerifyCodeRegister } from "../../../components/auth/password-pages/VerifyCodeRegister";
import Swal from "sweetalert2";
import { useRegisterData } from "@/app/hooks/useData";

export const Register = () => {
  const dispatch = useAppDispatch();
  const { data: translations } = useRegisterData();
  const t = translations || {};
  const [showLoginForm, setShowLoginForm] = useState(false);
  const [errors, setErrors] = useState({
    email: "",
    phone: "",
    login: "", // Added for login errors
    password: "", // Added for password validation errors
    retypePassword: "", // Added for retype password validation errors
  });
  const [isLoading, setIsLoading] = useState(false);
  const [showVerifyCode, setShowVerifyCode] = useState(false);
  const [communeQuery, setCommuneQuery] = useState("");
  const [verificationCode, setVerificationCode] = useState("");
  const [communeSuggestions, setCommuneSuggestions] = useState<
    CommuneSuggestion[]
  >([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const router = useRouter();

  // Use a single state for email/password for both forms
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [retypePassword, setRetypePassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [showRetypePassword, setShowRetypePassword] = useState(false);

  const [formData, setFormData] = useState({
    lang: "fr",
    name: "",
    christian_name: "",
    sur_name: "",
    username: "",
    // Note: email and password in formData are now managed by separate state above
    phone: "",
    address: "event x address",
    postal_code: "92400",
    country_id: 33,
    state_id: 11,
    city_id: 75056,
    role: 3,
    community: "EventX",
    organization: "",
  });

  useEffect(() => {
    const fetchCommuneSuggestions = async () => {
      if (communeQuery.length < 3) {
        setCommuneSuggestions([]);
        setShowSuggestions(false);
        return;
      }

      try {
        const response = await fetch(
          `https://admin.eventx.fr/api/get-state-with-country?search_keyword=${encodeURIComponent(
            communeQuery
          )}`
        );
        const data = await response.json();

        if (data.status === 200 && data.getResult) {
          setCommuneSuggestions(data.getResult);
          setShowSuggestions(true);
        }
      } catch (error) {
        console.error("Error fetching commune suggestions:", error);
        setCommuneSuggestions([]);
      }
    };

    const debounceTimer = setTimeout(fetchCommuneSuggestions, 300);
    return () => clearTimeout(debounceTimer);
  }, [communeQuery]);

  const handleMailLoginClick = () => {
    setShowLoginForm(true);
  };

  const handleBackClick = () => {
    setShowLoginForm(false);
    // Optionally clear login form state when going back
    setEmail("");
    setPassword("");
    setRetypePassword("");
    setShowPassword(false);
    setShowRetypePassword(false);
    setErrors((prev) => ({ ...prev, login: "" }));
  };

  const handleForgotPasswordClick = () => {
    router.push("/forgot-password");
  };

  const handleGoogleSignIn = () => {
    const backendUrl = process.env.NEXT_PUBLIC_API_URL_New;
    // Redirect to backend Google OAuth endpoint
    window.location.href = `${backendUrl}/auth/google`;
  };

  const handleMicrosoftSignIn = () => {
    const backendUrl = process.env.NEXT_PUBLIC_API_URL_New;
    // Redirect to backend Microsoft OAuth endpoint
    window.location.href = `${backendUrl}/auth/microsoft`;
  };

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  /**
   * Login function to be used in the inline login form
   */
  const handleLogin = async () => {
    if (!email || !password) {
      Swal.fire({
        icon: "warning",
        title: t.errors?.missing_information_title || "Missing Information",
        text:
          t.errors?.missing_information_text ||
          "Please enter both email and password",
        confirmButtonText: t.errors?.ok || "OK",
      });
      return;
    }

    setIsLoading(true);

    try {
      await dispatch(loginUser({ email, password, language: "en" })).unwrap();
      Swal.fire({
        title: t.success?.welcome_title || "Bienvenue",
        icon: "success",
        showConfirmButton: false,
        timer: 1500,
      }).then(() => {
        dispatch(fetchUserWallets()).unwrap();
        router.push("/home");
      });
    } catch (error: any) {
      Swal.fire({
        icon: "error",
        title: t.errors?.login_failed_title || "Échec de la connexion",
        text:
          t.errors?.login_failed_text ||
          error?.message ||
          error ||
          "Email ou mot de passe invalide",
        confirmButtonText: t.errors?.ok || "OK",
      });
      console.error("Login error:", error);
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * Register function to be used in the main registration form
   */
  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();

    if (
      !email ||
      !password ||
      !formData.phone ||
      !formData.christian_name ||
      !formData.sur_name ||
      !formData.organization
    ) {
      Swal.fire({
        icon: "warning",
        title: t.errors?.missing_information_title || "Missing Information",
        text:
          t.errors?.missing_information_text ||
          "Please fill in all required fields",
        confirmButtonText: t.errors?.ok || "OK",
      });
      return;
    }

    // Validate password before proceeding
    const passwordError = validatePassword(password);
    if (passwordError) {
      setErrors((prev) => ({ ...prev, password: passwordError }));
      Swal.fire({
        icon: "warning",
        title: t.errors?.password_validation_title || "Invalid Password",
        text: passwordError,
        confirmButtonText: t.errors?.ok || "OK",
      });
      return;
    }

    setErrors({
      email: "",
      phone: "",
      login: "",
      password: "",
      retypePassword: "",
    });
    setIsLoading(true);

    try {
      // 1. Check Email
      const emailCheckResult = await dispatch(checkEmail({ email })).unwrap();
      if (emailCheckResult.data?.exists) {
        setErrors((prev) => ({
          ...prev,
          email: t.errors?.email_already_exists || "Email already exists",
        }));
        setIsLoading(false);
        return;
      }

      // 2. Check Phone
      const phoneCheckResult = await dispatch(
        checkPhone({ phone: formData.phone })
      ).unwrap();
      if (phoneCheckResult.data?.exists) {
        setErrors((prev) => ({
          ...prev,
          phone:
            t.errors?.phone_already_exists || "Phone number already exists",
        }));
        setIsLoading(false);
        return;
      }

      // 3. Prepare and Register User
      const generatedUsername =
        formData.christian_name.toLowerCase() +
        "." +
        formData.sur_name.toLowerCase() +
        Math.floor(Math.random() * 10000);
      const fullName = `${formData.christian_name} ${formData.sur_name}`;

      const finalFormData = {
        ...formData,
        email, // Use state email
        password, // Use state password
        username: generatedUsername,
        name: fullName,
      };

      await dispatch(registerUser(finalFormData)).unwrap();

      Swal.fire({
        title:
          t.success?.registration_successful_title ||
          "Registration Successful!",
        text:
          t.success?.registration_successful_text ||
          "Your account has been created successfully",
        icon: "success",
        showConfirmButton: false,
        timer: 2000,
      }).then(() => {
        setShowVerifyCode(true);
      });
    } catch (error: any) {
      Swal.fire({
        icon: "error",
        title: t.errors?.registration_failed_title || "Registration Failed",
        text:
          error.message ||
          t.errors?.registration_failed_text ||
          "An error occurred during registration",
        confirmButtonText: t.errors?.ok || "OK",
      });
      console.error("Registration error:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCommuneInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setCommuneQuery(value);
  };

  const handleCommuneSelect = (commune: CommuneSuggestion) => {
    setFormData((prev) => ({
      ...prev,
      state_id: parseInt(commune.state_id),
      city_id: parseInt(commune.city_id),
      country_id: parseInt(commune.country_id),
      postal_code: commune.postal_code,
      address: commune.city_name,
    }));

    setCommuneQuery(commune.city_name);
    setShowSuggestions(false);
    setCommuneSuggestions([]);
  };

  /**
   * Validate password according to requirements:
   * - Minimum 8 characters
   * - At least one numeral
   * - At least one special symbol
   * - At least one capital letter
   */
  const validatePassword = (passwordValue: string): string => {
    if (!passwordValue) {
      return "";
    }

    if (passwordValue.length < 8) {
      return "Password must be at least 8 characters long";
    }

    if (!/[0-9]/.test(passwordValue)) {
      return "Password must contain at least one numeral";
    }

    if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(passwordValue)) {
      return "Password must contain at least one special symbol";
    }

    if (!/[A-Z]/.test(passwordValue)) {
      return "Password must contain at least one capital letter";
    }

    return "";
  };

  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newPassword = e.target.value;
    setPassword(newPassword);
    const passwordError = validatePassword(newPassword);
    setErrors((prev) => ({ ...prev, password: passwordError }));
  };

  // --- Render Logic ---
  return (
    <div className="split-container">
      {/* White section (30%) */}
      <div className="white-section">
        <div className="logo-container-reg">
          <Image
            src="/login/login_2.png"
            alt={t.alt?.company_logo || "Company Logo"}
            width={180}
            height={80}
            className="logo"
            priority
          />
        </div>
        <div className="color-blocks-container">
          {showLoginForm ? (
            <div className="color-block-register block-white-register">
              <div className="block-icon-white-register-container"></div>
              <div className="block-white-text-content-register">
                <input
                  type="text"
                  className="input-line"
                  placeholder={t.form?.email_placeholder || "Addrese email"}
                  autoComplete="username"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={isLoading}
                />
                <input
                  type="password"
                  className="input-line"
                  placeholder={t.options?.[0]?.subLabel || "Mot de passe"}
                  autoComplete="current-password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  disabled={isLoading}
                />
                <div
                  className="forget-pass-other"
                  onClick={handleForgotPasswordClick}
                  style={{ cursor: "pointer" }}
                >
                  {t.form?.forgot_password || "Mot de passe oublié ?"}
                </div>
                <button
                  className="login-button-register"
                  onClick={handleLogin}
                  disabled={isLoading}
                >
                  {isLoading
                    ? t.form?.logging_in || "Logging in..."
                    : t.form?.login_button || " se connecter"}
                </button>
              </div>
              <div className="block-icon-white-container-register-right">
                <Image
                  src="/login/arrow_email.png"
                  alt={t.alt?.icon || "Icon"}
                  width={24}
                  height={24}
                  className="block-icon"
                  onClick={handleBackClick}
                />
              </div>
            </div>
          ) : (
            <div
              className="color-block-register block-gray-register"
              onClick={handleMailLoginClick}
              style={{ cursor: "pointer" }}
            >
              <div className="block-icon-container-register">
                <Image
                  src="/login/mail.png"
                  alt={t.alt?.icon || "Icon"}
                  width={24}
                  height={24}
                  className="block-icon"
                />
              </div>
              <div className="block-text-content-register">
                <div className="primary-text-breakline-register">
                  <span>
                    {" "}
                    {t.options?.[0]?.label || "Continuer avec votre Mail"}{" "}
                  </span>{" "}
                  <br />
                  <span className="topspace-text">
                    {t.options?.[0]?.subLabel || "et mot de passe"}
                  </span>{" "}
                </div>
              </div>
            </div>
          )}

          {/* Social login blocks (always visible) */}
          {/* Using t.options for dynamic text based on translation data */}
          <div
            className="color-block block-red"
            onClick={handleGoogleSignIn}
            style={{ cursor: "pointer" }}
          >
            <div className="block-red-icon-container">
              <Image
                src="/login/google.png"
                alt={t.alt?.google_icon || "Google Icon"}
                width={24}
                height={24}
                className="block-icon"
              />
            </div>
            <div className="block-red-text-content">
              <div className="primary-red-text-reg">
                {t.options?.[1]?.label || "Continuer avec Google"}
              </div>
            </div>
          </div>
          <div
            className="color-block block-black"
            onClick={handleMicrosoftSignIn}
            style={{ cursor: "pointer" }}
          >
            <div className="block-black-icon-container">
              <Image
                src="/login/microsoft.png"
                alt={t.alt?.microsoft_icon || "Microsoft Icon"}
                width={24}
                height={24}
                className="block-icon"
              />
            </div>
            <div className="block-black-text-content-reg">
              <div className="primary-black-text-reg ">
                {t.options?.[2]?.label || "Continuer avec Microsoft"}
              </div>
            </div>
          </div>
          <div className="color-block block-blue">
            <div className="block-blue-icon-container-reg">
              <Image
                src="/login/fbicon.svg"
                alt={t.alt?.facebook_icon || "Facebook Icon"}
                width={14}
                height={14}
                className="block-icon"
              />
            </div>
            <div className="block-blue-text-content">
              <div className="primary-blue-text-reg">
                {t.options?.[3]?.label || "Continuer avec Facebook"}
              </div>
            </div>
          </div>
        </div>

        {/* Continue as guest (always visible) */}
        <div className="conti-guest">
          <div className="guest-text">
            {t.options?.[4]?.label || "Continuer en tant qu'invité"}
          </div>
        </div>
      </div>

      {/* Blue section (70%) - Main Registration Form / Verify Code */}
      <div className="blue-section">
        {showVerifyCode ? (
          <VerifyCodeRegister
            email={email} // Pass current email state
            verificationCode={verificationCode}
            setVerificationCode={setVerificationCode}
          />
        ) : (
          <div className="white-center-container">
            <div className="register-content">
              <div className="register-image">
                <Image
                  src="/login/logo_1.png"
                  alt={t.alt?.eventx_logo || "EventX Logo"}
                  width={65}
                  height={60}
                  className="dynamic-image"
                />
                <p className="register-title">
                  {t.pageTitle || "Sign up to EventX here !"}
                </p>
              </div>
              <div className="register-text">
                <p>
                  {t.description?.line1 ||
                    "You'll need to create a free account to upload an event"}
                </p>
                <p>
                  {t.description?.line2 ||
                    "- but its really simple and only takes a few minutes."}
                </p>
              </div>
              <form style={{ display: "contents" }} onSubmit={handleRegister}>
                <div className="personal-input-container">
                  <label className="text-label-main">
                    {t.personalDetails?.sectionTitle || "Personal details"}
                  </label>
                  <label className="text-label">
                    {t.personalDetails?.christianName || "Christian name"}
                  </label>
                  <input
                    type="text"
                    name="christian_name"
                    className="text-input"
                    placeholder=""
                    required
                    value={formData.christian_name}
                    onChange={handleInputChange}
                    disabled={isLoading}
                  />
                  <label className="text-label-other">
                    {t.personalDetails?.surname || "Surname"}
                  </label>
                  <input
                    type="text"
                    name="sur_name"
                    className="text-input"
                    placeholder=""
                    required
                    value={formData.sur_name}
                    onChange={handleInputChange}
                    disabled={isLoading}
                  />
                  <label className="text-label-other">
                    {t.personalDetails?.userType || "User type"}
                  </label>
                  <select
                    className="text-input"
                    required
                    value={formData.role}
                    onChange={handleInputChange}
                    name="role"
                    disabled={isLoading}
                  >
                    <option value="3">
                      {t.personalDetails?.advertiser || "Advertiser"}
                    </option>
                  </select>

                  <label className="text-label-other">
                    {t.personalDetails?.businessOrAssociationName ||
                      "Business or Association Name"}
                  </label>
                  <input
                    type="text"
                    className="text-input"
                    name="organization"
                    placeholder={
                      t.personalDetails?.organizationPlaceholder || ""
                    }
                    required
                    value={formData.organization}
                    onChange={handleInputChange}
                    disabled={isLoading}
                  />
                </div>
                <div className="contact-input-container">
                  <label className="text-label-main">
                    {t.contactInformation?.sectionTitle ||
                      "Contact Information"}
                  </label>
                  <label className="text-label">
                    {t.contactInformation?.mobileNumber || "Mobile Number"}
                  </label>
                  <input
                    type="number"
                    name="phone"
                    className="text-input"
                    placeholder={
                      t.contactInformation?.mobilePlaceholder ||
                      "06 69 84 40 31"
                    }
                    required
                    value={formData.phone}
                    onChange={handleInputChange}
                    disabled={isLoading}
                  />
                  {errors.phone && (
                    <div
                      className="error-message"
                      style={{
                        color: "red",
                        fontSize: "12px",
                        marginTop: "5px",
                        textAlign: "left",
                      }}
                    >
                      {errors.phone}
                    </div>
                  )}
                  <label className="text-label-other">
                    {t.contactInformation?.communeName || "Commune name"}
                  </label>
                  <div style={{ position: "relative" }}>
                    <input
                      type="text"
                      className="text-input"
                      placeholder={
                        t.contactInformation?.communePlaceholder ||
                        "Search for your city or commune..."
                      }
                      required
                      value={communeQuery}
                      onChange={handleCommuneInputChange}
                      disabled={isLoading}
                      autoComplete="new-password"
                    />
                    {showSuggestions && communeSuggestions.length > 1 && (
                      <div
                        style={{
                          position: "absolute",
                          top: "100%",
                          left: 0,
                          right: 0,
                          backgroundColor: "white",
                          width: "115%",
                          border: "1px solid #c4c4c4",
                          borderTop: "none",
                          borderRadius: "0 0 4px 4px",
                          maxHeight: "200px",
                          overflowY: "auto",
                          zIndex: 1000,
                          boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
                        }}
                      >
                        {communeSuggestions.map((commune, index) => (
                          <div
                            key={index}
                            className="suggestion-box"
                            onClick={() => handleCommuneSelect(commune)}
                            onMouseEnter={(e) =>
                              (e.currentTarget.style.backgroundColor =
                                "#f5f5f5")
                            }
                            onMouseLeave={(e) =>
                              (e.currentTarget.style.backgroundColor = "white")
                            }
                          >
                            <div style={{ fontWeight: "bold" }}>
                              {commune.city_name} , {commune.postal_code}
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
                <div className="connection-input-container">
                  <label className="text-label-main">
                    {t.contactInformation?.sectionTitle ||
                      "Contact Information"}
                  </label>
                  <label className="text-label">
                    {t.contactInformation?.emailAddress || "E-mail address"}
                  </label>
                  <input
                    type="email"
                    name="email"
                    className="text-input"
                    placeholder={
                      t.contactInformation?.emailPlaceholder || "your@email.com"
                    }
                    required
                    autoComplete="email"
                    value={email} // Use state email
                    onChange={(e) => setEmail(e.target.value)}
                    disabled={isLoading}
                  />
                  {errors.email && (
                    <div
                      className="error-message"
                      style={{
                        color: "red",
                        fontSize: "12px",
                        marginTop: "5px",
                        textAlign: "left",
                      }}
                    >
                      {errors.email}
                    </div>
                  )}
                  <label className="text-label-other">
                    {t.contactInformation?.password || "Password"}
                  </label>
                  <div
                    className="grid grid-cols-12 gap-0 password-field-container"
                    style={{ width: "115%" }}
                  >
                    <input
                      type={showPassword ? "text" : "password"}
                      className="text-input col-span-10"
                      style={{
                        borderTopRightRadius: 0,
                        borderBottomRightRadius: 0,
                        borderRight: "none",
                      }}
                      name="password"
                      placeholder=""
                      required
                      autoComplete="new-password"
                      value={password} // Use state password
                      onChange={handlePasswordChange}
                      disabled={isLoading}
                    />
                    <button
                      type="button"
                      className="col-span-2 flex items-center justify-center border border-l-0 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed password-toggle-button"
                      style={{
                        border: "1px solid #b1b1b1",
                        borderLeft: "none",
                        borderRadius: "0 4px 4px 0",
                        backgroundColor: "#ffffff",
                        height: "100%",
                        padding: "6px 15px",
                      }}
                      onClick={() => setShowPassword(!showPassword)}
                      disabled={isLoading}
                    >
                      {showPassword ? (
                        <svg
                          className="w-5 h-5 text-gray-500"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <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 text-gray-500"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <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.password && (
                    <div
                      className="error-message"
                      style={{
                        color: "red",
                        fontSize: "12px",
                        marginTop: "5px",
                        textAlign: "left",
                      }}
                    >
                      {errors.password}
                    </div>
                  )}
                  <label className="text-label-other">
                    {t.contactInformation?.retypePassword ||
                      "Retype your Password"}
                  </label>
                  <div
                    className="grid grid-cols-12 gap-0 password-field-container"
                    style={{ width: "115%" }}
                  >
                    <input
                      type={showRetypePassword ? "text" : "password"}
                      className="text-input col-span-10"
                      style={{
                        borderTopRightRadius: 0,
                        borderBottomRightRadius: 0,
                        borderRight: "none",
                      }}
                      placeholder=""
                      required
                      autoComplete="new-password"
                      value={retypePassword}
                      onChange={(e) => {
                        setRetypePassword(e.target.value);
                        // Clear error when user starts typing
                        if (errors.retypePassword) {
                          setErrors((prev) => ({
                            ...prev,
                            retypePassword: "",
                          }));
                        }
                      }}
                      disabled={isLoading}
                    />
                    <button
                      type="button"
                      className="col-span-2 flex items-center justify-center border border-l-0 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed password-toggle-button"
                      style={{
                        border: "1px solid #b1b1b1",
                        borderLeft: "none",
                        borderRadius: "0 4px 4px 0",
                        backgroundColor: "#ffffff",
                        height: "100%",
                        padding: "6px 15px",
                      }}
                      onClick={() => setShowRetypePassword(!showRetypePassword)}
                      disabled={isLoading}
                    >
                      {showRetypePassword ? (
                        <svg
                          className="w-5 h-5 text-gray-500"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <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 text-gray-500"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <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.retypePassword && (
                    <div
                      className="error-message"
                      style={{
                        color: "red",
                        fontSize: "12px",
                        marginTop: "5px",
                        textAlign: "left",
                      }}
                    >
                      {errors.retypePassword}
                    </div>
                  )}
                </div>
                {/* <div className="newsletter-container">
                  <div className="newsletter-checkbox-container">
                    <input
                      type="checkbox"
                      id="newsletter"
                      className="newsletter-checkbox"
                      disabled={isLoading}
                    />
                    <label htmlFor="newsletter" className="newsletter-label">
                      {t.newsletter?.question ||
                        "Would you like to receive our Newsletter?"}
                    </label>
                  </div>
                </div> */}
                <div className="retrieve-password-button">
                  <p className="terms-text">
                    {t.termsAndPolicies?.note1 ||
                      "Clicking on the button, you agree to our"}
                    <a
                      href="https://www.eventx.fr/use-of-the-site"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="terms-link"
                    >
                      {" "}
                      {t.termsAndPolicies?.note2 || "terms and policies"}
                    </a>
                  </p>
                  <div className="button-container">
                    <button
                      type="submit"
                      className="blue-button"
                      disabled={isLoading}
                    >
                      {isLoading ? (
                        <span>
                          {t.cta?.creating_account || "Creating Account..."}
                        </span>
                      ) : (
                        <>
                          <span>
                            {t.cta?.buttonText || "Create your Account now"}
                          </span>
                          <Image
                            src="/login/arrow.png"
                            alt={t.alt?.retrieve || "Retrieve"}
                            width={22}
                            height={22}
                            className="button-icon"
                            style={{ marginLeft: "2px" }}
                          />
                        </>
                      )}
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
