"use client";

import React, { useEffect } 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 LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectPath = searchParams.get("redirect") || "/dashboard";
  const isLoggedIn = useSelector(selectIsLoggedIn);
  const status = useSelector(selectStatus);
  const authMessage = useSelector(selectAuthMessage);

  const dispatch = useDispatch<AppDispatch>(); // Initialize useDispatch

  // Effect to handle redirection after login or if already logged in
  useEffect(() => {
    if (isLoggedIn && status === "succeeded") {
      router.replace(redirectPath); // Redirect to intended path on successful login
    }
  }, [isLoggedIn, status, router, redirectPath]);

  // Function to handle login attempt, now dispatches Redux thunk
  const handleLogin = async (email: string, password: string) => {
    // Dispatch the login async thunk
    const resultAction = await dispatch(login({ email, password }));

    // Check if login was successful based on the thunk's result
    if (login.fulfilled.match(resultAction)) {
      return true; // Login successful
    } else {
      return false; // Login failed
    }
  };

  // Function to clear authentication message, now dispatches Redux action
  const handleClearAuthMessage = () => {
    dispatch(clearAuthMessage());
  };

  // If user is already logged in, show a redirecting message
  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">
            You are logged in. Redirecting to dashboard...
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="page-container">
      <div className="page-container__content">
        <h1 className="page-container__title">Payment Backoffice</h1>
        <p className="page-container__text">
          Please log in to access the backoffice.
        </p>
      </div>

      <Modal open={true} title="Login to Payment Cashier">
        <LoginModal
          onLogin={handleLogin}
          authMessage={authMessage}
          clearAuthMessage={handleClearAuthMessage}
        />
      </Modal>
    </div>
  );
}
