import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
import {LanguageModal} from "@/translate/LanguageModal";
import { Person } from "@mui/icons-material";
import authService from "@services/auth";
import { authActions } from "@/redux/reducers/auth";
import { languageActions } from "@/redux/reducers/language";
import { useTranslation } from "@/hooks/useTranslation";

export const UserMenu = () => {
    const dispatch = useDispatch();
    const { t } = useTranslation();
    const { logout } = useAuth0();
    const { user: currentUser } = useSelector((s) => s.auth);
    const currentLang = useSelector((s) => s.language.current);
    const [isLangOpen, setLangOpen] = useState(false);

    useEffect(() => {
        if (currentUser?.userType !== "NORMAL_USER") return;
        authService.getCurrentUserLocal().then((freshUser) => {
            if (freshUser?.totalPoints !== undefined) {
                dispatch(authActions.updateUser({ totalPoints: freshUser.totalPoints }));
            }
        });
    }, []);

    const isCompanyAccount = currentUser?.userType === "COMPANY_USER" || currentUser?.userType === "COMPANY_ADMIN";
    const avatarUrl = isCompanyAccount ? currentUser?.companyLogoUrl : currentUser?.profilePictureUrl;

    const handleLanguageSelect = (lang) => {
        dispatch(languageActions.setLanguage(lang));
        setLangOpen(false);
    };

    return (
        <>
            <div className="flex flex-col overflow-hidden gap-0 rounded-2xl bg-white cursor-default" onClick={(e)=> e.stopPropagation()}>
                <div
                    style={{
                        background: "linear-gradient(94deg, #B0EEFF 0%, #FFD0EC 100%)",
                    }}
                    className="w-full flex gap-4 items-start p-3"
                >
                    {avatarUrl ? (
                        <img
                            src={avatarUrl}
                            alt="user"
                            style={{
                                height: "77px",
                                width: "77px",
                                borderRadius: "50%",
                            }}
                            className="size-[77px]"
                        />
                    ) : (
                        <div
                            style={{
                                height: "77px",
                                width: "77px",
                                borderRadius: "50%",
                                backgroundColor: "#ddd",
                                display: "flex",
                                justifyContent: "center",
                                alignItems: "center",
                            }}
                        >
                            <Person style={{ fontSize: 36, color: "#888" }} />
                        </div>
                    )}

                    <div className="flex flex-col gap-1">
                        <div className="text-base font-bold pt-2">
                            {currentUser?.firstname} {currentUser?.lastname}
                        </div>
                        {currentUser?.userType === "NORMAL_USER" && (
                            <div className="w-fit py-1 px-4 rounded-xl bg-tale-purple flex items-center justify-center text-white font-bold">
                                {t("layout.userMenu.points", { points: currentUser?.totalPoints })}
                            </div>)}
                    </div>
                </div>

                <LanguageModal
                    isOpen={isLangOpen}
                    onClose={() => setLangOpen(false)}
                    currentLang={currentLang}
                    onSelect={handleLanguageSelect}
                />

                {!isLangOpen && (
                    <>
                        <div className="flex flex-col gap-1 p-3">
                            <div className="text-sm font-bold">{t("layout.userMenu.myAccount")}</div>

                            <div className="flex flex-col gap-1">
                                <Link to="/account" className="text-sm w-fit">
                                    {t("layout.userMenu.editMyInformation")}
                                </Link>
                                <Link to="/account/change-password-connected" className="text-sm w-fit">
                                    {t("layout.userMenu.changePassword")}
                                </Link>
                            </div>
                        </div>


                        <div className="flex flex-col gap-1 p-3 !pt-0 ">
                            <div className="text-sm font-bold">{t("layout.userMenu.settings")}</div>

                            <div className="flex flex-col gap-1">
                                <button
                                    className="text-sm w-fit text-left rtl:text-right"
                                    onClick={() => setLangOpen(true)}
                                >
                                    {t("layout.userMenu.language")}
                                </button>
                                <Link to="/policy" className="text-sm w-fit">
                                    {t("layout.userMenu.privacyPolicy")}
                                </Link>
                            </div>

                            <div
                                className="text-sm font-medium mt-3 cursor-pointer"
                                onClick={async () => {
                                    localStorage.removeItem("access_token");
                                    await logout({
                                        logoutParams: {
                                            returnTo: `${process.env.REACT_APP_WEBSITE}/login`,
                                        },
                                    });
                                }}
                            >
                                {t("layout.userMenu.logout")}
                            </div>
                        </div>
                    </>
                )}
            </div>
        </>
    );
};