"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 { useLoginData } from "@/app/hooks/useData";

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 { data: translations } = useLoginData();
  const t = translations || {};
  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);
    }
  };
  const handleMailLoginClick = () => {
    setShowLoginForm(true);
  };

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

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

  return (
    <div className="split-container-loginpage">
      {/* White section (30%) */}
      <div className="white-section-login">
        <div style={{ marginTop: "-4vh" }}>
          <div className="login-top-line-mobile">
            {t.headings?.[0]?.text
              ? t.headings[0].text.split(" ").slice(0, 3).join(" ")
              : "Plongez dans les événements"}
          </div>
          <div className="top-line-bottom-login-mobile">
            {t.headings?.[0]?.text
              ? t.headings[0].text.split(" ").slice(3).join(" ")
              : "de votre coin !"}
          </div>
        </div>
        <div className="logo-container-login">
          <Image
            src="/login/login_2.png"
            alt={t.alt?.company_logo || "Company Logo"}
            width={180}
            height={80}
            className="logo"
            // style={{ width: 'auto', height: 'auto' }}
          />
        </div>
        <div className="color-blocks-container">
          {showLoginForm ? (
            <div className="color-block-login block-white">
              <div className="block-icon-white-container"></div>
              <div className="block-white-text-content">
                <input
                  type="text"
                  className="input-line"
                  placeholder={t.form?.email_placeholder || "Addrese email"}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={isLoading}
                />
                <input
                  type="password"
                  className="input-line"
                  placeholder={t.options?.[0]?.subLabel || "Mot de passe"}
                  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"
                  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-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-login block-gray-login"
              onClick={handleMailLoginClick}
              style={{ cursor: "pointer" }}
            >
              <div className="block-icon-container-login">
                <Image
                  src="/login/mail.png"
                  alt={t.alt?.icon || "Icon"}
                  width={24}
                  height={24}
                  className="block-icon"
                />
              </div>
              <div className="block-text-content-login">
                <div className="primary-text-breakline-login">
                  <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>
          )}

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

        <>
          <div className="conti-guest-login">
            <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>
                      <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>
        </>
        {/* )} */}
      </div>

      {/* Blue section (70%) */}
      <div className="blue-section-login">
        <div className="top-right-text-login">
          <div className="login-top-line">
            {t.headings?.[0]?.text
              ? t.headings[0].text.split(" ").slice(0, 4).join(" ")
              : "Plongez dans les événements"}
          </div>
          <div className="top-line-bottom-loginn">
            {t.headings?.[0]?.text
              ? t.headings[0].text.split(" ").slice(4).join(" ")
              : ""}
          </div>
          <div className="top-middle-line-login">
            {t.headings?.[1]?.text ||
              "Votre prochain coup de cœur est au coin de la rue"}
          </div>
          <div className="top-middle-line-other-againlogin">
            {t.headings?.[2]?.text ||
              "Et 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={t.alt?.background || "Background"}
            fill
            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
            className="background-image"
            priority={false}
          />
        </div>
      </div>
    </div>
  );
};
