"use client";

import React, { useState } from "react";
import "./Login.css";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { loginUser } from "../../../redux/services/auth/authServices";
import { fetchUserWallets } from "../../../redux/services/main/campaigns/mycampaign";
import { useAppDispatch } from "../../../hooks/useDispatch";
import Swal from "sweetalert2";
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";
export const Login = () => {
  const dispatch = useAppDispatch();
  const [showLoginForm, setShowLoginForm] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();
  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 handleMailLoginClick = () => {
    setShowLoginForm(true);
  };

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

  const handleForgotPasswordClick = () => {
    window.location.href = "/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`;
  };

  return (
    <div className="split-container-loginpage">
      {/* White section (30%) */}
      <div className="white-section-login">
        <div style={{ marginTop: "-4vh" }}>
          <div className="login-top-line-mobile">
            {"Plongez dans les événements de votre coin !"
              .split(" ")
              .slice(0, 3)
              .join(" ")}
          </div>
          <div className="top-line-bottom-login-mobile">
            {"Plongez dans les événements de votre coin !"
              .split(" ")
              .slice(3)
              .join(" ")}
          </div>
        </div>
        <div className="logo-container-login">
          <Image
            src="/login/login_2.png"
            alt="Logo de l'entreprise"
            width={180}
            height={80}
            className="logo"
            // style={{ width: 'auto', height: 'auto' }}
          />
        </div>
        <div className="color-blocks-container">
          {showLoginForm ? (
            <ShowLoginForm
              email={email}
              password={password}
              isLoading={isLoading}
              onEmailChange={setEmail}
              onPasswordChange={setPassword}
              onForgotPasswordClick={handleForgotPasswordClick}
              onLoginClick={handleLogin}
              onBackClick={handleBackClick}
            />
          ) : (
            <LoginEmail handleMailLoginClick={handleMailLoginClick} />
          )}

          {/* {!showLoginForm && ( */}
          <>
            <GoogleSignIn />
            <MicrosoftSignIn />
            <FacebookSignIn />
          </>
          {/* )} */}
        </div>

        <>
          <div className="conti-guest-login">
            <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>
                      <div>Ouvrez votre compte</div>
                      <div>100% gratuit et sans engagement</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </>
        {/* )} */}
      </div>

      {/* Blue section (70%) */}
      <div className="blue-section-login">
        <div className="top-right-text-login">
          <div className="login-top-line">
            {"Plongez dans les événements de votre coin !"
              .split(" ")
              .slice(0, 4)
              .join(" ")}
          </div>
          <div className="top-line-bottom-loginn">
            {"Plongez dans les événements de votre coin !"
              .split(" ")
              .slice(4)
              .join(" ")}
          </div>
          <div className="top-middle-line-login">
            Votre prochain coup de cœur est au coin de la rue.
          </div>
          <div className="top-middle-line-other-againlogin">
            Redécouvrez votre quartier sous un nouveau jour.
          </div>
          <div className="top-middle-line-other1-login1">
            {/* {t.headings?.[4]?.text
              ? t.headings[4].text.split(" ").slice(3).join(" ")
              : "de votre coin !"} */}
          </div>
        </div>
        <div className="background-image-container-login">
          <Image
            src="/login/login_1.png"
            alt="Arrière-plan"
            fill
            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
            className="background-image"
            priority={false}
          />
        </div>
      </div>
    </div>
  );
};
