"use client";

import React, { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useDispatch, useSelector } from "react-redux";
import LoginModal from "../features/Auth/LoginModal";
import Modal from "../components/Modal/Modal";
import { AppDispatch } from "../redux/types";
import {
  selectAuthMessage,
  selectIsLoggedIn,
  selectStatus,
  selectUser,
} from "../redux/auth/selectors";
import {
  clearAuthMessage,
  login,
  changePassword,
} from "../redux/auth/authSlice";
import "./page.scss";
import { ChangePassword } from "../features/Auth/ChangePassword/ChangePassword";

export default function LoginPageClient() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectPath = searchParams.get("redirect") || "/dashboard";
  const reason = searchParams.get("reason");
  const isLoggedIn = useSelector(selectIsLoggedIn);
  const status = useSelector(selectStatus);
  const authMessage = useSelector(selectAuthMessage);
  const user = useSelector(selectUser);
  const dispatch = useDispatch<AppDispatch>();
  const [redirectMessage, setRedirectMessage] = useState<string>("");
  const [mustChangePassword, setMustChangePassword] = useState<boolean>(
    reason === "change-password"
  );

  console.log("[DEBUG] [reason]:", reason === "change-password");

  useEffect(() => {
    // Set message based on redirect reason
    if (reason === "expired-token") {
      setRedirectMessage("Your session has expired. Please log in again.");
    } else if (reason === "invalid-token") {
      setRedirectMessage("Invalid session detected. Please log in again.");
    } else if (reason === "no-token") {
      setRedirectMessage("Please log in to access the backoffice.");
    } else if (reason === "change-password") {
      setRedirectMessage(
        "Please change your password to access the backoffice."
      );
    }
  }, [reason]);

  useEffect(() => {
    setMustChangePassword(reason === "change-password" ? true : false);
  }, [reason]);

  useEffect(() => {
    if (isLoggedIn && status === "succeeded" && !mustChangePassword) {
      router.replace(redirectPath);
    }
  }, [isLoggedIn, status, mustChangePassword, router, redirectPath]);

  const handleLogin = async (email: string, password: string) => {
    const resultAction = await dispatch(login({ email, password }));
    return login.fulfilled.match(resultAction);
  };

  const handleClearAuthMessage = () => {
    dispatch(clearAuthMessage());
  };

  const handleChangePassword = async (passwordData: {
    currentPassword?: string;
    newPassword: string;
  }) => {
    if (!user?.email) {
      console.error("No user email available for password change");
      return false;
    }

    const resultAction = await dispatch(
      changePassword({
        email: user.email,
        newPassword: passwordData.newPassword,
        currentPassword: passwordData.currentPassword,
      })
    );
    const result = changePassword.fulfilled.match(resultAction);

    // if(result && resultAction.payload.success) {
    //   setMustChangePassword(!resultAction.payload.success);
    // }
    return result;
  };

  if (isLoggedIn && !mustChangePassword) {
    return (
      <div className="page-container">
        <div className="page-container__content">
          <h1 className="page-container__title">Payment Backoffice</h1>
          <p className="page-container__message--logged-in">
            {redirectMessage || "Please log in to access the backoffice."}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="page-container">
      {mustChangePassword ? (
        <Modal open={true} title="Change Your Temporary Password">
          <ChangePassword
            open={true}
            onClose={() => {}}
            onSubmit={handleChangePassword}
          />
        </Modal>
      ) : (
        <Modal open={true} title="Login to Payment Cashier">
          <LoginModal
            onLogin={handleLogin}
            authMessage={authMessage}
            clearAuthMessage={handleClearAuthMessage}
          />
        </Modal>
      )}
    </div>
  );
}
