"use client";

import React, { useState, useEffect } from "react";
import "./forgetPassword.css";
import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
import {
  forgotPassword,
  verifyResetToken,
} from "../../redux/services/auth/authServices";
import { VerifyCode } from "../../components/auth/password-pages/VerifyCode";
import { ResetPassword } from "../../components/auth/password-pages/ResetPassword";
import { ResetTokenPassword } from "../../components/auth/password-pages/ResetTokenPassword";
import Swal from "sweetalert2";
import { loginUser } from "../../redux/services/auth/authServices";
import { fetchUserWallets } from "@/app/redux/services/main/campaigns/mycampaign";
import FormInput from "@/app/components/auth/commons/cards/Lable";
import HeaderCard from "@/app/components/auth/commons/cards/HeadingCard";
import SubHeaderCard from "@/app/components/auth/commons/cards/SubHeadingCard";
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";
interface ForgotPasswordResponse {
  data: any;
  message: string;
}
export const ForgetPassword = () => {
  const [showLoginForm, setShowLoginForm] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isTokenVerificationLoading, setIsTokenVerificationLoading] =
    useState(false);
  const [showVerifyCode, setShowVerifyCode] = useState(false);
  const [showResetPassword, setResetPassword] = useState(false);
  const [showReseTokenPassword, setResetTokenPassword] = useState(false);
  const [verificationCode, setVerificationCode] = useState("");
  const router = useRouter();
  const dispatch = useAppDispatch();
  const searchParams = useSearchParams();
  const token = searchParams.get("token");

  useEffect(() => {
    if (token) {
      handleTokenVerification();
    }
  }, [token]);
  const handleTokenVerification = async () => {
    if (!token) return;
    setIsTokenVerificationLoading(true);
    try {
      const result = (await dispatch(
        verifyResetToken({
          token,
        }) as any
      ).unwrap()) as ForgotPasswordResponse;
      Swal.fire({
        icon: "success",
        title: "Lien Vérifié !",
        text: "Lien vérifié avec succès !",
        confirmButtonText: "OK",
      });
      setResetTokenPassword(true);
    } catch (error: unknown) {
      const errorMessage =
        error instanceof Error ? error.message : String(error);
      Swal.fire({
        icon: "error",
        title: "Échec de la Vérification du Lien",
        text: "",
        confirmButtonText: "OK",
      });
      setResetTokenPassword(false);
    } finally {
      setIsTokenVerificationLoading(false);
    }
  };
  const handleMailLoginClick = () => {
    setShowLoginForm(true);
  };

  const handleBackClick = () => {
    router.back();
  };

  const handleForgotPasswordClick = () => {
    window.location.href = "/forgot-password";
  };

  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);
    }
  };

  const handleRetrievePassword = async () => {
    setIsTokenVerificationLoading(true);
    try {
      const result = (await dispatch(
        forgotPassword({ email }) as any
      ).unwrap()) as ForgotPasswordResponse;
      Swal.fire({
        icon: "success",
        title: " Vérifier votre boîte email",
        text: "Ensuite, cliquez simplement sur le lien de vérification pour réinitialiser votre mot de passe.",
        confirmButtonText: "OK",
      });
      setShowVerifyCode(true);
    } catch (error: unknown) {
      console.error("Password reset failed:", error);

      const errorMessage =
        error instanceof Error ? error.message : String(error);

      // Translate common error messages to French
      let translatedErrorMessage = errorMessage;
      if (
        errorMessage.toLowerCase().includes("email must be an email") ||
        errorMessage.toLowerCase().includes("must be an email")
      ) {
        translatedErrorMessage = "L'adresse email doit être valide";
      }

      Swal.fire({
        icon: "error",
        title: "Échec de l'envoi",
        text: translatedErrorMessage,
        confirmButtonText: "OK",
      });
    } finally {
      setIsTokenVerificationLoading(false);
    }
  };
  return (
    <div className="split-forget-container-forget">
      {/* White section (30%) */}
      <div className="white-forget-section">
        <div className="logo-forget-container-forg">
          <Image
            src="/login/login_2.png"
            alt="Company Logo"
            width={180}
            height={80}
            className="logo"
          />
        </div>
        <div className="color-forget-blocks-container">
          {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>

        {/* {!showLoginForm && ( */}
        <>
          <div className="conti-guest-forget">
            <div className="guest-text">Continuer en tant qu'invité</div>
          </div>
          <div>
            <div className="color-blocks-container-login-online">
              <div className="color-block-login block-blue-login-online">
                <div
                  className="block-blue-text-content-online"
                  onClick={() => router.push("/register")}
                >
                  <div
                    className="primary-blue-text-online-login"
                    style={{ textAlign: "center" }}
                  >
                    <div>Ouvrez votre compte</div>
                    <div>100% gratuit et sans engagement</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </>
        {/* )} */}
      </div>
      <div className="blue-forget-section">
        {showReseTokenPassword ? (
          <ResetTokenPassword token={token} />
        ) : showResetPassword ? (
          <ResetPassword email={email} code={verificationCode} />
        ) : showVerifyCode ? (
          <VerifyCode
            email={email}
            verificationCode={verificationCode}
            setResetPassword={setResetPassword}
            setVerificationCode={setVerificationCode}
          />
        ) : (
          <div className="white-forget-center-container-forg ">
            <button
              className="mobile-back-forget-button"
              onClick={handleBackClick}
              aria-label="Go back"
            >
              <Image
                src="/login/arrow_email.png"
                alt="Retour"
                width={24}
                height={24}
                className="block-icon"
              />
            </button>
            <div className="forgot-password-content">
              <HeaderCard
                logoSrc="/login/logo_1.png"
                logoAlt=""
                logoWidth={65}
                logoHeight={60}
                title="Mot de passe oublié ?"
                useOriginalStyling={true}
              />
              <SubHeaderCard
                line1="Aucun problème ! Remplissez le formulaire ci-dessous"
                line2="Nous vous reconnecterons à votre compte en quelques clics"
                useOriginalStyling={true}
              />
              <div className="email-input-container">
                <FormInput
                  label="Adresse email"
                  name="email"
                  type="email"
                  value={email}
                  onChange={(fieldName, fieldValue) => setEmail(fieldValue)}
                  placeholder="Saisissez votre adresse e-mail"
                  required
                  containerWidth="full"
                />
              </div>
              <div className="retrieve-forget-password-button">
                <button
                  className="blue-forget-button-forget"
                  onClick={handleRetrievePassword}
                  disabled={isTokenVerificationLoading}
                >
                  {isTokenVerificationLoading
                    ? "chargement..."
                    : "Récupérer mon mot de passe"}
                  <Image
                    src="/login/arrow.png"
                    alt="Retrieve"
                    width={22}
                    height={22}
                    className="button-icon"
                    style={{ marginLeft: "2px" }}
                  />
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
