"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,
} from "../redux/auth/selectors";
import { clearAuthMessage, login } from "../redux/auth/authSlice";
import "./page.scss";

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 dispatch = useDispatch<AppDispatch>();
  const [redirectMessage, setRedirectMessage] = useState<string>("");

  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.");
    }
  }, [reason]);

  useEffect(() => {
    if (isLoggedIn && status === "succeeded") {
      router.replace(redirectPath);
    }
  }, [isLoggedIn, status, 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());
  };

  if (isLoggedIn) {
    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">
      <Modal open={true} title="Login to Payment Cashier">
        <LoginModal
          onLogin={handleLogin}
          authMessage={authMessage}
          clearAuthMessage={handleClearAuthMessage}
        />
      </Modal>
    </div>
  );
}
