"use client";
import { useEffect } from "react";
import { useSessionStore } from "@store/Sesion.Store";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { LOGIN_ACTIONS, useLoginActionStore } from "@store/LoginAction.Store";
import Link from "next/link";

interface SecureProps {
    children: React.ReactNode;
    loginAction?: LOGIN_ACTIONS;
}

export default function SecurePage(props: SecureProps): React.ReactElement {
    const router = useRouter();
    const pathname = usePathname(); // Obtiene el path actual
    const searchParams = useSearchParams();
    const SessionInfo = useSessionStore();
    const loginAction = useLoginActionStore();

    const getCurrentPath = () => {
        return `${pathname}${searchParams ? `?${searchParams.toString()}` : ""}`;
    };

    const AccessDeneided = () => {
        return (
            <>
                <span>Acceso denegado</span>
            </>
        );
    };

    const Loading = () => {
        return (
            <>
                <div className="error-div-container">
                    <div className="card error-card">
                        <h2 style={{ color: "var(--wine-red)" }}>Verificando su sesión</h2>
                        <p>
                            Estamos validando sus credenciales de acceso. Por favor, espere unos
                            momentos. Si el proceso tarda más de lo esperado, intente iniciar sesión
                            nuevamente. Ante cualquier duda, contáctenos en
                            <Link href="mailto:info@turnosxpress.com.ar">
                                info@turnosxpress.com.ar
                            </Link>
                            .
                        </p>
                    </div>
                </div>
            </>
        );
    };

    useEffect(() => {
        if (SessionInfo.loginState === "success" || SessionInfo.loginState === "error") {
            if (!SessionInfo.loged) {
                if (props.loginAction) {
                    loginAction.setLoginAction(props.loginAction);
                    loginAction.setUrl(getCurrentPath());
                }
                router.push("/landing/login");
            }
        }
    }, [SessionInfo.loginState]);

    return (
        <>
            {SessionInfo.loged && <>{props.children}</>}
            {SessionInfo.loginState === "error" && AccessDeneided()}
            {SessionInfo.loginState === "success" && !SessionInfo.loged && AccessDeneided()}
            {SessionInfo.loginState === "started" && Loading()}
        </>
    );
}
