"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 LoginPageClient() {
  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>();

  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">
            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>
  );
}
