/* The LRFPopUp component serves as a generic modal dialog for displaying custom components. */
import { RootState } from "@/redux/slices";
import { commonActions } from "@/redux/slices/Common/commonSlice";
import { AppDispatch } from "@/redux/store";
import { LRFFlowContent } from "@/src/types/StaticContent/lrfflow.content.type";
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import CreateProfile from "../page/FindAHome/CreateProfile/CreateProfile";
import ForgotPasswordSuccess from "../page/FindAHome/CreateProfile/ForgotPasswordSuccess";
import ProfileCreated from "../page/FindAHome/CreateProfile/ProfileCreated";
import SetNewPassword from "../page/FindAHome/CreateProfile/SetNewPassword";
import VerificationCode from "../page/FindAHome/VerificationCode/VerificationCode";
import styles from "./CommonPopup.module.scss";

// Define the props for the CommonPopup component
interface CommonPopupProps {
    confirmationModal?: boolean;
    component?: React.ReactNode;
    message?: string;
    title?: string;
    paragraph?: string;
    primaryBtnText?: string;
    cancelButtonText?: string;
    deleteBtnText?: string;
    footer?: boolean;
    onSubmit?: () => void;
    onCancel?: () => void;
    setModal?: (value: boolean) => void;
    CreateProfileContent?: LRFFlowContent
}

const LRFPopUp = ({ CreateProfileContent, ...props }: CommonPopupProps) => {

    const dispatch = useDispatch<AppDispatch>();
    const { LRFFlow } = useSelector((state: RootState) => state?.common)
    const [titleNdecription, setTitleNdescription] = React.useState({ title: '', description: null });
    const { emailLRFData } = useSelector((state: RootState) => state?.authentication)

    // Function to close the popup
    const closePopup = () => {
        dispatch(commonActions.setLRFModalOpen(false))
    }

    // Add or remove a class to the body based on the modal's open state
    useEffect(() => {
        if (LRFFlow) {
            document.body.classList.add('modal-open');
        } else {
            document.body.classList.remove('modal-open');
        }

        // Cleanup function to remove the class when the component is unmounted
        return () => {
            document.body.classList.remove('modal-open');
        };
    }, [LRFFlow]);

    // Add a listener for the Escape key press
    useEffect(() => {
        const handleEscKeyPress = (event: KeyboardEvent) => {
            if (event.key === 'Escape') {
                closePopup();
            }
        };

        // Attach the event listener
        window.addEventListener('keydown', handleEscKeyPress);

        // Cleanup the event listener on component unmount
        return () => {
            window.removeEventListener('keydown', handleEscKeyPress);
        };
    }, []);

    // Update the title and description based on the LRFFlow
    useEffect(() => {
        if (LRFFlow === 'create') {
            setTitleNdescription({ title: CreateProfileContent.POPUP_TITLE_DESC.CREATE_ACCOUNT_TITLE, description: CreateProfileContent.POPUP_TITLE_DESC.CREATE_ACCOUNT_DESC })
        } else if (LRFFlow === 'login') {
            setTitleNdescription({ title: CreateProfileContent.POPUP_TITLE_DESC.LOGIN_TITLE, description: CreateProfileContent.POPUP_TITLE_DESC.LOGIN_DESC })
        } else if (LRFFlow === 'forgot-password') {
            setTitleNdescription({ title: CreateProfileContent.POPUP_TITLE_DESC.FORGOT_PASSWORD_TITLE, description: CreateProfileContent.POPUP_TITLE_DESC.FORGOT_PASSWORD_DESC })
        } else if (LRFFlow === 'otp-verification') {
            setTitleNdescription({ title: CreateProfileContent.POPUP_TITLE_DESC.OTP_VERIFICATION_TITLE, description: <>{CreateProfileContent.POPUP_TITLE_DESC.OTP_VERIFICATION_DESC} <b>{emailLRFData}</b></> })
        } else if (LRFFlow === 'forgot-password-otp-verification') {
            setTitleNdescription({ title: CreateProfileContent.POPUP_TITLE_DESC.PASSWORD_RESET_TITLE, description: <>{CreateProfileContent.POPUP_TITLE_DESC.OTP_VERIFICATION_DESC} <b>{emailLRFData}</b></> })
        } else if (LRFFlow === 'set-new-password') {
            setTitleNdescription({ title: CreateProfileContent.POPUP_TITLE_DESC.SET_NEW_PASSWORD, description: CreateProfileContent.POPUP_TITLE_DESC.SET_NEW_PASSWORD_DESC })
        }
    }, [LRFFlow])

    /**
     * 
     * @returns LRF Component
     * This function returns the LRF component based on the current LRFFlow step value. 
     */
    const LRFComponent = () => {
        switch (LRFFlow) {
            case 'create':
                return <CreateProfile CreateProfileContent={CreateProfileContent} />
            case 'login':
                return <CreateProfile CreateProfileContent={CreateProfileContent} />
            case 'forgot-password':
                return <CreateProfile CreateProfileContent={CreateProfileContent} />
            case 'otp-verification':
                return <VerificationCode CreateProfileContent={CreateProfileContent} />
            case 'forgot-password-otp-verification':
                return <VerificationCode CreateProfileContent={CreateProfileContent} />
            case 'set-new-password':
                return <SetNewPassword SetNewPasswordContent={CreateProfileContent.SET_NEW_PASSWORD} />
            case 'profile-created':
                return <ProfileCreated CreateProfileContent={CreateProfileContent} />
            case 'forgot-password-success':
                return <ForgotPasswordSuccess CreateProfileContent={CreateProfileContent} />
            default:
                return ''
        }
    }

    return (
        <>
            <div className={`${(LRFFlow === 'profile-created' || LRFFlow === 'forgot-password-success') ? 'autoClosepopup' : ''}`}>
                <div className={`${styles.commonPopUp} commonPopup flex items-center fixed top-0 left-0 justify-center h-dvh w-full z-9999`}>
                    <div className={`${styles.overlayBackground} h-full w-full absolute top-0 left-0`} onClick={closePopup}></div>
                    <div className={`${styles.popupWrapper} popupWrapper max-w-[90%] z-[3] h-fit w-[588px] relative`}>
                        <button type="button" className={`PopupCloseBtn SecondaryBtn !p-0 absolute right-0 top-0 z-1 !w-[57px] !h-[57px] rounded-full`} onClick={closePopup}>
                            <i className={`Icon IconCross !bg-white w-[14px] h-[14px]`}></i>
                        </button>
                        <div className={`${styles.popupBox} w-full`}>
                            <div className="popup-wrapper-body">
                                <div className="swalContent">
                                    {(LRFFlow !== 'profile-created' && LRFFlow !== 'forgot-password-success') && <div className={`p-4 md:p-5 lg:p-6 w-full`}>
                                        <div className={`max-w-[calc(100%-65px)] md:max-w-[calc(100%-55px)]`}>
                                            {titleNdecription?.title && <h4 className={`title !mb-[0px]`}>{titleNdecription?.title}</h4>}
                                            {titleNdecription?.description && <p className={`fs-16 text-grey667Color`}>{titleNdecription?.description}</p>}
                                        </div>
                                    </div>}
                                    <div className={`p-4 md:p-5 lg:p-6 w-full max-h-[calc(100vh-260px)] md:max-h-[calc(100vh-260px)] overflow-auto border-t border-whiteEC`}>
                                        {LRFComponent()}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
};

export default LRFPopUp;

