"use client";
import { useRouter } from "next/navigation";
import { useUserMenuStore } from "@store/UserMenu.Store";
import { useEffect, useState } from "react";
import { loginByToken } from "@services/Session.Login";
import { getTokenFromLocalStorage } from "@config/token";
import Avatar from "../Avatar/Avatar";
import ButtonOption from "../ButtonOption/ButtonOption";
import style from "./UserMenu.module.css";
import CloseIcon from "@mui/icons-material/Close";
import { useSessionStore, useSessionTokenStore } from "@store/Sesion.Store";
import { useAlert } from "@store/Alert.Store";
import { ApiError } from "@core/Models/Server.Error.model";
import { getClientSocket } from "@core/Services/Socket.service";
import { Socket } from "socket.io-client";
import { ISubscriptionInfo } from "@core/Models/Subscription.Model";
import dayjs from "dayjs";
import { loadOrganizationsByUser } from "@core/app/admin/org/Org.Service";
import { MyOranizationsView } from "@core/Models/Company.model";
import SelectOrganizationPopup from "./SelectOrganizationPopup";

export default function UserMenu(): React.ReactElement {
    const router = useRouter();
    const aler = useAlert();
    const SessionInfo = useSessionStore();
    const SessionToken = useSessionTokenStore();
    const menuState = useUserMenuStore();
    const classData = menuState.visible ? style.userMenuVisible : style.userMenuHidden;
    const classBackgroundData = menuState.visible
        ? style.userMenuBackgroundVisible
        : style.userMenuBackgroundHidden;

    const [clientSocket, setClientSocket] = useState<Socket | undefined>(undefined);
    const [showOrgPopup, setShowOrgPopup] = useState(false);
    const [userOrgs, setUserOrgs] = useState<MyOranizationsView[]>([]);
    useEffect(() => {
        try {
            //TODO: Comprobar si se arregla el problema...
            //if (SessionInfo.loged) return;
            const isLoged = SessionInfo.loged;
            SessionInfo.setLoginState("started");
            const tryToken = getTokenFromLocalStorage();
            if (!tryToken) {
                SessionInfo.setLoginState("error");
                return;
            }
            loginByToken(tryToken)
                .then((sessionUser) => {
                    SessionInfo.setUser(sessionUser);
                    SessionInfo.setLoginState("success");
                    if (!isLoged) {
                        aler.showSuccess("Sesión iniciada!");
                    }
                })
                .catch((error) => {
                    if (error instanceof ApiError) {
                        const validationError = error as ApiError;
                        console.log(validationError.format());
                    }
                    console.log("El login fallo sin errores...");
                    SessionInfo.setLoginState("error");
                    SessionInfo.clear();
                    SessionToken.setToken("");
                });
        } catch (error) {
            SessionInfo.setLoginState("error");
            console.log("El login fallo CON errores...");
            if (error instanceof ApiError) {
                const validationError = error as ApiError;
                console.log(validationError.format());
            }
            return;
        }
    }, []);

    useEffect(() => {
        if (!SessionInfo.userId) {
            return;
        }

        if (clientSocket) {
            return;
        }

        const socket = getClientSocket(SessionInfo.userId);
        setClientSocket(socket);
    }, [SessionInfo.loged]);

    useEffect(() => {
        if (!clientSocket) {
            return;
        }

        clientSocket.on("suscription_status_updated", (subscription: ISubscriptionInfo) => {
            SessionInfo.setSubscription(subscription);
        });

        return () => {
            clientSocket.off("suscription_status_updated");
        };
    }, [clientSocket]);

    const toggleMenu = () => {
        menuState.setVisible(!menuState.visible);
    };

    const logOut = () => {
        if (clientSocket) {
            clientSocket.off("suscription_status_updated");
            clientSocket.disconnect();
        }
        SessionInfo.clear();
        SessionToken.setToken("");
        goTo("/landing/login");
    };

    const goTo = (path: string) => {
        toggleMenu();
        router.push(path);
    };

    const handleTodayAgendaClick = async () => {
        try {
            const orgs = await loadOrganizationsByUser(SessionInfo.userId);
            if (orgs.length === 1) {
                const targetDate = dayjs().startOf('day').toISOString();
                goTo(`/admin/org/profile/${orgs[0].id}/appointments/${targetDate}`);
            } else if (orgs.length > 1) {
                setUserOrgs(orgs);
                setShowOrgPopup(true);
            } else {
                aler.showError("No perteneces a ninguna organización.");
            }
        } catch (error) {
            aler.showError("Error al cargar organizaciones");
        }
    };

    const handleOrgSelect = (orgId: string) => {
        setShowOrgPopup(false);
        const targetDate = dayjs().startOf('day').toISOString();
        goTo(`/admin/org/profile/${orgId}/appointments/${targetDate}`);
    };

    const getUserName = () => {
        return SessionInfo.loged ? SessionInfo.userFullName : "Anonimo";
    };

    const getUserEmail = () => {
        return SessionInfo.loged ? SessionInfo.userEmail : "";
    };

    const getUserAvatarSrc = () => {
        if (SessionInfo.loged) {
            return SessionInfo.avatar;
        }
        return "/anonimus-avatar.svg";
    };

    return (
        <>
            <div className={classBackgroundData} onClick={toggleMenu}></div>
            <div className={classData}>
                <div className={style.userMenuHeader}>
                    <CloseIcon
                        fontSize="large"
                        className={style.userMenuCloseButton}
                        onClick={toggleMenu}
                    />
                </div>
                <div className={style.userMenuUserData}>
                    <Avatar src={getUserAvatarSrc()} name={"avatarUserMenu"} alt="Avatar" />
                    <div>
                        <h1>{getUserName()}</h1>
                        <span>{getUserEmail()}</span>
                    </div>
                </div>
                <div className={style.userMenuOptionsContainer}>
                    {SessionInfo.loged && (
                        <>
                            {SessionInfo.subscription && (
                                <>
                                    <ButtonOption
                                        text="Dashboard"
                                        icon="/home-icon.svg"
                                        textAlign="left"
                                        iconAlign="left"
                                        onClick={() => goTo("/landing/dashboard")}
                                    />
                                    <a 
                                        className={style.assistantMenuItem} 
                                        onClick={() => goTo("/admin/assistant")}
                                    >
                                        <img src="/assistant-icon.svg" alt="Asistente" />
                                        <span>Asistente</span>
                                    </a>
                                    {Object.keys(SessionInfo.organizationSubscriptions || {}).length > 0 && (
                                        <ButtonOption
                                            text="Agenda de hoy"
                                            icon="/event-icon.svg"
                                            textAlign="left"
                                            iconAlign="left"
                                            onClick={handleTodayAgendaClick}
                                        />
                                    )}
                                    <ButtonOption
                                        text="Mis organizaciones"
                                        icon="/store-icon.svg"
                                        textAlign="left"
                                        iconAlign="left"
                                        onClick={() => goTo("/admin/org")}
                                    />
                                </>
                            )}
                            <ButtonOption
                                text="Editar perfil"
                                icon="/profile-icon.svg"
                                textAlign="left"
                                iconAlign="left"
                                onClick={() => goTo("/user/profile")}
                            />
                            <ButtonOption
                                text="Mis turnos"
                                icon="/event-icon.svg"
                                textAlign="left"
                                iconAlign="left"
                                onClick={() => goTo("/landing/my-appointments")}
                            />
                            <ButtonOption
                                text="Messenger"
                                icon="/messenger-icon.svg"
                                textAlign="left"
                                iconAlign="left"
                                onClick={() => goTo("/messenger")}
                            />
                        </>
                    )}
                    {!SessionInfo.loged && (
                        <ButtonOption
                            text="Registrarme"
                            icon="/profile-icon.svg"
                            textAlign="left"
                            iconAlign="left"
                            onClick={() => goTo("/landing/signup")}
                        />
                    )}
                </div>
                <div className={style.userMenuFooter}>
                    {SessionInfo.loged && (
                        <ButtonOption
                            text="Cerrar sesión"
                            icon="/logout-icon.svg"
                            onClick={() => logOut()}
                            buttonStyle="plain"
                            iconAlign="left"
                            textAlign="left"
                        />
                    )}
                    {!SessionInfo.loged && (
                        <ButtonOption
                            text="Iniciar sesión"
                            icon="/login-icon.svg"
                            onClick={() => goTo("/landing/login")}
                            buttonStyle="plain"
                            iconAlign="left"
                            textAlign="left"
                        />
                    )}
                </div>
            </div>
            {showOrgPopup && (
                <SelectOrganizationPopup
                    organizations={userOrgs}
                    onClose={() => setShowOrgPopup(false)}
                    onSelect={handleOrgSelect}
                />
            )}
        </>
    );
}
