"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 { ShowLoginForm } from "@/app/components/auth/commons/ShowLoginForm";
import { GoogleSignIn } from "@/app/components/auth/commons/GoogleSignIn";
import { MicrosoftSignIn } from "@/app/components/auth/commons/MicrosoftSignIn";
import { FacebookSignIn } from "@/app/components/auth/commons/Facebook";
import LoginEmail from "@/app/components/auth/commons/cards/LoginEmail";
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 { EyeClosedIcon, EyeOpenIcon } from "@/app/components/auth/commons/Eyes";

export const Register = () => {
  const dispatch = useAppDispatch();
  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 [isPasswordFocused, setIsPasswordFocused] = useState(false);
  const [isRetypePasswordFocused, setIsRetypePasswordFocused] = 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 = () => {
    window.location.href = "/forgot-password";
  };

  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: "Informations manquantes",
        text: "Veuillez saisir votre e-mail et votre mot de passe",
        confirmButtonText: "OK",
      });
      return;
    }

    setIsLoading(true);

    try {
      await dispatch(loginUser({ email, password, language: "en" })).unwrap();
      Swal.fire({
        title: "Bienvenue",
        icon: "success",
        showConfirmButton: false,
        timer: 1500,
      }).then(() => {
        dispatch(fetchUserWallets()).unwrap();
        router.push("/home");
      });
    } catch (error: any) {
      Swal.fire({
        icon: "error",
        title: "Échec de la connexion",
        text: "Email ou mot de passe invalide",
        confirmButtonText: "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: "Informations manquantes",
        text: "Veuillez remplir tous les champs obligatoires",
        confirmButtonText: "OK",
      });
      return;
    }

    // Validate password before proceeding
    const passwordError = validatePassword(password);
    if (passwordError) {
      setErrors((prev) => ({ ...prev, password: passwordError }));
      Swal.fire({
        icon: "warning",
        title: "Mot de passe invalide",
        text: passwordError,
        confirmButtonText: "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: "Cette adresse e-mail existe déjà",
        }));
        setIsLoading(false);
        return;
      }

      // 2. Check Phone
      const phoneCheckResult = await dispatch(
        checkPhone({ phone: formData.phone })
      ).unwrap();
      if (phoneCheckResult.data?.exists) {
        setErrors((prev) => ({
          ...prev,
          phone: "Ce numéro de téléphone existe déjà",
        }));
        setIsLoading(false);
        return;
      }

      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,
        password,
        username: generatedUsername,
        name: fullName,
      };

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

      Swal.fire({
        title: "Compte en cours de configuration",
        text: "Veuillez vérifier votre boîte e-mail pour trouver un lien de vérification ou un code",
        icon: "success",
        showConfirmButton: true,
        confirmButtonText: "OK",
      }).then((result) => {
        if (result.isConfirmed) {
          setShowVerifyCode(true);
        }
      });
    } catch (error: any) {
      Swal.fire({
        icon: "error",
        title: "Échec de l'inscription",
        text: "Une erreur est survenue lors de l'inscription",
        confirmButtonText: "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 "Le mot de passe doit comporter au moins 8 caractères";
    }

    if (!/[0-9]/.test(passwordValue)) {
      return "Le mot de passe doit contenir au moins un chiffre";
    }

    if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(passwordValue)) {
      return "Le mot de passe doit contenir au moins un symbole spécial";
    }

    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="Logo de l'entreprise"
            width={180}
            height={80}
            className="logo"
            priority
          />
        </div>
        <div className="color-blocks-container-reg">
          {showLoginForm ? (
            <ShowLoginForm
              email={email}
              password={password}
              isLoading={isLoading}
              onEmailChange={setEmail}
              onPasswordChange={setPassword}
              onForgotPasswordClick={handleForgotPasswordClick}
              onLoginClick={handleLogin}
              onBackClick={handleBackClick}
            />
          ) : (
            <LoginEmail handleMailLoginClick={handleMailLoginClick} />
          )}

          <GoogleSignIn />
          <MicrosoftSignIn />
          <FacebookSignIn />
        </div>
        <div className="conti-guest">
          <div className="guest-text">Continuer en tant qu'invité</div>
        </div>
      </div>

      {/* Blue section (70%) - Main Registration Form / Verify Code */}
      {showVerifyCode ? (
        <VerifyCodeRegister
          email={email} // Pass current email state
          verificationCode={verificationCode}
          setVerificationCode={setVerificationCode}
        />
      ) : (
        <div className="blue-section">
          <div className="white-center-container">
            <div className="register-content">
              <div className="register-image">
                <Image
                  src="/login/logo_1.png"
                  alt="Logo EventX"
                  width={65}
                  height={60}
                  className="dynamic-image"
                />
                <p className="register-title">
                  Inscrivez-vous sur EventX ici !
                </p>
              </div>
              <div className="register-text">
                <p>
                  Vous devez créer un compte gratuit pour publier un événement
                </p>
                <p>
                  - mais c'est très simple et ne prend que quelques minutes.
                </p>
              </div>
              <form style={{ display: "contents" }} onSubmit={handleRegister}>
                <div className="personal-input-container">
                  <label className="text-label-main">
                    Informations personnelles
                  </label>
                  <label className="text-label">Prénom</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">Nom</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  text-label-spacetop">
                    Type d'utilisateur
                  </label>
                  <select
                    className="text-input"
                    required
                    value={formData.role}
                    onChange={handleInputChange}
                    name="role"
                    disabled={isLoading}
                  >
                    <option value="3">Annonceur</option>
                  </select>

                  <label className="text-label-other text-label-spacetop-two">
                    Nom de l'entreprise ou de l'association
                  </label>
                  <input
                    type="text"
                    className="text-input"
                    name="organization"
                    placeholder={""}
                    required
                    value={formData.organization}
                    onChange={handleInputChange}
                    disabled={isLoading}
                  />
                </div>
                <div className="contact-input-container">
                  <label className="text-label-main">
                    Informations de contact
                  </label>
                  <label className="text-label">Numéro de mobile</label>
                  <input
                    type="number"
                    name="phone"
                    className="text-input"
                    placeholder="06 00 00 00 00"
                    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  text-label-spacetop-two">
                    Nom de la commune
                  </label>
                  <div style={{ position: "relative" }}>
                    <input
                      type="text"
                      className="text-input"
                      placeholder="Recherchez votre ville ou 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">
                    Informations de contact
                  </label>
                  <label className="text-label">Adresse e-mail</label>
                  <input
                    type="email"
                    name="email"
                    className="text-input"
                    placeholder="votre@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  text-label-spacetop-three">
                    Mot de passe
                  </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}
                      onChange={handlePasswordChange}
                      onFocus={() => setIsPasswordFocused(true)}
                      onBlur={() => setIsPasswordFocused(false)}
                      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: isPasswordFocused
                          ? "2px solid #0071c9"
                          : "1px solid #b1b1b1",
                        borderLeft: "none",
                        borderWidth: isPasswordFocused
                          ? "2px 2px 2px 0"
                          : "1px 1px 1px 0",
                        borderRadius: "0 4px 4px 0",
                        backgroundColor: "#ffffff",
                        height: "100%",
                        padding: "6px 15px",
                      }}
                      onClick={() => setShowPassword(!showPassword)}
                      disabled={isLoading}
                    >
                      {showPassword ? <EyeClosedIcon /> : <EyeOpenIcon />}
                    </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 text-label-spacetop-three">
                    Confirmez votre mot de passe
                  </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);
                        if (errors.retypePassword) {
                          setErrors((prev) => ({
                            ...prev,
                            retypePassword: "",
                          }));
                        }
                      }}
                      onFocus={() => setIsRetypePasswordFocused(true)}
                      onBlur={() => setIsRetypePasswordFocused(false)}
                      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: isRetypePasswordFocused
                          ? "2px solid #0071c9"
                          : "1px solid #b1b1b1",
                        borderLeft: "none",
                        borderWidth: isRetypePasswordFocused
                          ? "2px 2px 2px 0"
                          : "1px 1px 1px 0",
                        borderRadius: "0 4px 4px 0",
                        backgroundColor: "#ffffff",
                        height: "100%",
                        padding: "6px 15px",
                      }}
                      onClick={() => setShowRetypePassword(!showRetypePassword)}
                      disabled={isLoading}
                    >
                      {showRetypePassword ? <EyeClosedIcon /> : <EyeOpenIcon />}
                    </button>
                  </div>
                  {errors.retypePassword && (
                    <div
                      className="error-message"
                      style={{
                        color: "red",
                        fontSize: "12px",
                        marginTop: "5px",
                        textAlign: "left",
                      }}
                    >
                      {errors.retypePassword}
                    </div>
                  )}
                </div>
                <div className="retrieve-password-button">
                  <p className="terms-text">
                    En cliquant sur le bouton, vous acceptez nos
                    <a
                      href="https://www.eventx.fr/use-of-the-site"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="terms-link"
                    >
                      {" "}
                      conditions et politiques
                    </a>
                  </p>
                  <div className="button-container">
                    <button
                      type="submit"
                      className="blue-button"
                      disabled={isLoading}
                    >
                      {isLoading ? (
                        <span>Création du compte...</span>
                      ) : (
                        <>
                          <span>Créez votre compte maintenant</span>
                          <Image
                            src="/login/arrow.png"
                            alt="Récupérer"
                            width={22}
                            height={22}
                            className="button-icon"
                            style={{ marginLeft: "2px" }}
                          />
                        </>
                      )}
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
