"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 { useDispatch } from "react-redux";
import { useForgetPasswordData } from "@/app/hooks/useData";
interface ForgotPasswordResponse {
  data: any;
  message: string;
}
export const ForgetPassword = () => {
  const [showLoginForm, setShowLoginForm] = useState(false);
  const [email, setEmail] = useState("");
  const [isLoading, setIsLoading] = 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 = useDispatch();
  const searchParams = useSearchParams();
  const token = searchParams.get("token");
  const { data: translations } = useForgetPasswordData();
  const t = translations || {};
  useEffect(() => {
    if (token) {
      handleTokenVerification();
    }
  }, [token]);
  const handleTokenVerification = async () => {
    if (!token) return;
    setIsLoading(true);
    try {
      const result = (await dispatch(
        verifyResetToken({
          token,
        }) as any
      ).unwrap()) as ForgotPasswordResponse;
      Swal.fire({
        icon: "success",
        title: "Token Verified!",
        text: result.message || "Token verified successfully!",
        confirmButtonText: "OK",
      });
      setResetTokenPassword(true);
    } catch (error: unknown) {
      const errorMessage =
        error instanceof Error ? error.message : String(error);
      Swal.fire({
        icon: "error",
        title: "Token Verification Failed",
        text: errorMessage,
        confirmButtonText: "OK",
      });
      setResetTokenPassword(false);
    } finally {
      setIsLoading(false);
    }
  };
  const handleMailLoginClick = () => {
    setShowLoginForm(true);
  };

  const handleBackClick = () => {
    setShowLoginForm(false);
  };

  const handleForgotPasswordClick = () => {
    router.push("/forget-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 handleRetrievePassword = async () => {
    setIsLoading(true);
    try {
      const result = (await dispatch(
        forgotPassword({ email }) as any
      ).unwrap()) as ForgotPasswordResponse;
      Swal.fire({
        icon: "success",
        title: "Email Sent!",
        text:
          result.message ||
          "Password reset email sent successfully! Check your inbox.",
        confirmButtonText: "OK",
      });
      setShowVerifyCode(true);
    } catch (error: unknown) {
      console.error("Password reset failed:", error);

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

      Swal.fire({
        icon: "error",
        title: "Failed to Send",
        text: errorMessage,
        confirmButtonText: "OK",
      });
    } finally {
      setIsLoading(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 && (
            <>
              <div className="color-forget-block block-forget-gray">
                <div className="block-forget-icon-container">
                  <Image 
                    src="/login/mail.png"
                    alt="Icon"
                    width={24}
                    height={24}
                    className="block-icon"
                  />
                </div>
                <div className="block-forget-text-content1">
                  <div className="primary-text">Contactez-nous par adresse e-mai</div>
                </div>
              </div>
              <div 
                className="forget-pass" 
                onClick={handleForgotPasswordClick}
                style={{ cursor: 'pointer' }}
              >
                Forgot your password?
              </div>
            </>
          )} */}

          {showLoginForm ? (
            <div className="color-forget-block block-forget-white">
              <div className="block-icon-white-container">
                {/* <button 
                  onClick={handleBackClick}
                  className="back-button"
                >
                  ←
                </button> */}
              </div>
              <div className="block-white-forget-text-content">
                <input
                  type="text"
                  className="input-line"
                  placeholder="Addrese email"
                />
                <input
                  type="password"
                  className="input-line"
                  placeholder="Mot de passe"
                />
                <div
                  className="forget-pass-other"
                  onClick={handleForgotPasswordClick}
                  style={{ cursor: "pointer" }}
                >
                  Forgot your password?
                </div>
                <button className="login-button">Login</button>
              </div>
              <div className="block-icon-white-container-forget-right">
                <Image
                  src="/login/arrow_email.png"
                  alt="Icon"
                  width={24}
                  height={24}
                  className="block-icon"
                  onClick={handleBackClick}
                />
              </div>
            </div>
          ) : (
            <>
              <div
                className="color-forget-block block-forget-gray"
                onClick={handleMailLoginClick}
                style={{ cursor: "pointer" }}
              >
                <div className="block-forget-icon-container">
                  <Image
                    src="/login/mail.png"
                    alt="Icon"
                    width={24}
                    height={24}
                    className="block-icon"
                  />
                </div>
                <div className="block-forget-text-content">
                  <div className="primary-text-forget">
                    {t.options?.[0]?.label || "Continuer avec votre Mail"}
                  </div>
                  <div className="secondary-text-forget">
                    {t.options?.[0]?.subLabel || "et mot de passe"}
                  </div>
                </div>
              </div>
              <div
                className="forget-pass-forget"
                onClick={handleForgotPasswordClick}
                style={{ cursor: "pointer" }}
              >
                Forgot your password?
              </div>
            </>
          )}

          {/* {!showLoginForm && ( */}
          <>
            <div
              className="color-forget-block block-red"
              onClick={handleGoogleSignIn}
              style={{ cursor: "pointer" }}
            >
              <div className="block-red-icon-container">
                <Image
                  src="/login/google.png"
                  alt="google-Icon"
                  width={24}
                  height={24}
                  className="block-icon"
                />
              </div>
              <div className="block-red-text-content">
                <div className="primary-red-text-forget">
                  {t.options?.[1]?.label || "Continuer avec Google"}
                </div>
              </div>
            </div>
            <div
              className="color-forget-block block-black"
              onClick={handleMicrosoftSignIn}
              style={{ cursor: "pointer" }}
            >
              <div className="block-black-icon-container">
                <Image
                  src="/login/microsoft.png"
                  alt="google-Icon"
                  width={24}
                  height={24}
                  className="block-icon"
                />
              </div>
              <div className="block-black-text-content">
                <div className="primary-black-text-forget">
                  {t.options?.[2]?.label || "Continuer avec Microsoft"}
                </div>
              </div>
            </div>
            <div className="color-forget-block block-blue">
              <div className="block-blue-icon-container">
                <Image
                  src="/login/fbicon.svg"
                  alt="google-Icon"
                  width={14}
                  height={14}
                  className="block-icon"
                />
              </div>
              <div className="block-blue-text-content">
                <div className="primary-blue-text-forget">
                  {t.options?.[3]?.label || "Continuer avec Facebook"}
                </div>
              </div>
            </div>
          </>
          {/* )} */}
        </div>

        {/* {!showLoginForm && ( */}
        <>
          <div className="conti-guest-forget">
            <div className="guest-text">
              {t.options?.[4]?.label || "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>
                      {t.options?.[5]?.["button-title-line1"] ||
                        "Ouvrez votre compte"}
                    </div>
                    <div>
                      {t.options?.[5]?.["button-title-line2"] ||
                        "100% gratuit et sans engagement"}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          {/* <div className="conti-forget-guest">
            <div className="guest-forget-text">
              {t.options?.[4]?.label || "Continuer en tant qu'invité"}
            </div>
          </div>
          <div>
            <div className="color-forget-blocks-container-online">
              <div
                className="color-forget-block block-forget-blue-online"
                onClick={() => router.push("/register")}
              >
                <div className="block-forget-blue-text-content-online">
                  <div className="primary-forget-blue-text-online-forget">
                    {t.options?.[5]?.["button-title"] ||
                      "Create your online account"}
                  </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 ">
            <div className="forgot-password-content">
              <div className="forgot-password-image">
                <Image
                  src="/login/logo_1.png" // Update with your actual image path
                  alt=""
                  width={65}
                  height={60}
                />
                <p className="forgot-password-title">
                  {t.pageTitle || "Forgot your password?"}
                </p>
              </div>
              <div className="forgot-password-text-forg">
                <p>
                  {t.description?.line1 ||
                    "No problem! Complete the form below"}
                </p>
                <p>
                  {t.description?.line2 ||
                    "and we'll get you logged into your account in a few clicks"}
                </p>
              </div>
              <div className="email-input-container">
                <label className="email-label">
                  {t.form?.emailLabel || "E-mail address"}
                </label>
                <input
                  type="email"
                  className="email-input"
                  placeholder={
                    t.form?.emailPlaceholder || "Enter your email address"
                  }
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </div>
              <div className="retrieve-forget-password-button">
                <button
                  className="blue-forget-button-forget"
                  onClick={handleRetrievePassword}
                  disabled={isLoading}
                >
                  {isLoading
                    ? "Sending..."
                    : t.cta?.buttonText || "Retrieve your password"}
                  <Image
                    src="/login/arrow.png"
                    alt="Retrieve"
                    width={16}
                    height={16}
                    className="button-icon"
                    style={{ marginLeft: "7px" }}
                  />
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
