import React, { useEffect, useState } from "react";
import orgImg from "../../../assets/image/orgTemp.png";
import { useCamMode, useToggleView } from "../../../store/builder/store";
import CollaborationPopup from "../../templates/CollaborationPopup";
import { getAvatarColor } from "../../../modules/collaboration/functions/getAvatarColor";
import { useSelectedUserStore } from "../../../store/collaboration/useCollabStore";
import { useToggleStore } from "../../../store/ui/useUIToggleStore";
import { useSocketStore } from "../../../store/socket/useSocketStore";
import { useSceneContext } from "../../../modules/scene/sceneContext";
import useModuleStore from "../../../store/ui/useModuleStore";
import { ToggleSidebarIcon } from "../../icons/HeaderIcons";
import { getUserData } from "../../../functions/getUserData";
import { useParams } from "react-router-dom";

const Header: React.FC = () => {
    const { builderSocket } = useSocketStore();
    const { collabUsersStore } = useSceneContext();
    const { collabUsers } = collabUsersStore();
    const { userId, userName, organization } = getUserData();
    const { toggleUILeft, toggleUIRight, setToggleUI } = useToggleStore();
    const { activeModule } = useModuleStore();
    const { toggleView } = useToggleView();
    const { projectId } = useParams();

    const guestUsers = collabUsers.filter((user) => user.userId !== userId);

    const [userManagement, setUserManagement] = useState(false);
    const { selectedUser, setSelectedUser, clearSelectedUser } = useSelectedUserStore();
    const { setCamMode } = useCamMode();

    useEffect(() => {
        if ((activeModule !== "builder" && activeModule !== "simulation") || (toggleView && selectedUser)) {
            clearSelectedUser();
            setCamMode("ThirdPerson");
        }
    }, [toggleView, activeModule, selectedUser]);

    function handleUserFollow(user: CollabUsersScheme, index: number) {
        if (toggleView || (activeModule !== "builder" && activeModule !== "simulation")) return;

        const position = {
            x: user.camData.position.x,
            y: user.camData.position.y,
            z: user.camData.position.z,
        };
        const target = {
            x: user.camData.position.x,
            y: user.camData.position.y,
            z: user.camData.position.z,
        };
        const rotation = {
            x: user.camData.position.x,
            y: user.camData.position.y,
            z: user.camData.position.z,
        };

        // retun on no data
        if (!position || !target || !rotation || !builderSocket?.connected || !organization || !projectId) return;

        // Set the selected user in the store
        setSelectedUser({
            color: getAvatarColor(index, user.userId),
            name: user.userName,
            id: user.userId,
            location: { position, rotation, target },
        });
        setCamMode("FollowPerson");

        builderSocket.emit("v1:room:userdata:set", { followingUser: user.userId, organization, projectId });
    }

    return (
        <>
            {userManagement && <CollaborationPopup setUserManagement={setUserManagement} />}
            <div className="header-container">
                <div className="options-container">
                    <button
                        id="toggle-rightSidebar-ui-button"
                        className={`toggle-sidebar-ui-button ${!toggleUIRight ? "active" : ""}`}
                        onClick={() => {
                            if (activeModule !== "market") {
                                setToggleUI(toggleUILeft, !toggleUIRight);
                                localStorage.setItem("navBarUiRight", JSON.stringify(!toggleUIRight));
                            }
                        }}
                    >
                        <div className="tooltip">{toggleUIRight ? "Hide" : "Show"} sidebar (ctrl + ])</div>
                        <ToggleSidebarIcon />
                    </button>
                    <button
                        id="share-button"
                        className="share-button"
                        onClick={() => {
                            setUserManagement(true);
                        }}
                    >
                        Share
                    </button>
                    {/* <div className="app-docker-button">
            <AppDockIcon />
          </div> */}
                </div>
                <div className="split"></div>
                <div className="users-container">
                    <div className="guest-users-container">
                        {guestUsers.length > 3 && <div className="other-guest">+{guestUsers.length - 3}</div>}
                        {guestUsers.slice(0, 3).map((user, index) => (
                            <button
                                id="user-profile-button"
                                key={`${index}-${user.userName}`}
                                className="user-profile"
                                style={{ background: getAvatarColor(index, user.userId) }}
                                onClick={() => {
                                    handleUserFollow(user, index);
                                }}
                            >
                                {user.userName[0]}
                            </button>
                        ))}
                    </div>
                    <div className="user-profile-container">
                        <div className="user-profile">{userName?.charAt(0).toUpperCase()}</div>
                        <div className="user-organization">
                            <img src={orgImg} alt="" />
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
};

export default Header;
