import React, { createContext, useState, useContext, useMemo } from 'react';
import PropTypes from 'prop-types';
import { menuItems } from "../constants/menuItems.js";
import { permissionTypes } from '../constants/userConstants.js';

// Helper function to safely parse localStorage data
const getInitialUser = () => {
    try {
        const savedUser = localStorage.getItem('user');
        return savedUser ? JSON.parse(savedUser) : null;
    } catch (e) {
        console.log("user context - error parsing user:", e.message);
        return null;
    }
};

const getInitialPermissions = () => {
    try {
        const userPermissions = localStorage.getItem('permissions');
        return userPermissions ? JSON.parse(userPermissions) : null;
    } catch (e) {
        console.log("user context - error parsing permissions:", e.message);
        return null;
    }
};

const UserContext = createContext();

export function UserProvider({ children }) {
    // Initialize state synchronously from localStorage to prevent double renders
    const [user, setUser] = useState(getInitialUser);
    const [permissions, setPermissions] = useState(getInitialPermissions);
    const [openRoleChangedPopup, setOpenRoleChangedPopup] = useState(false);

    const login = (userData) => {
        setUser(userData);
        localStorage.setItem('user', JSON.stringify(userData));
    };

    const setUserPermissions = async (incomingPermissions) => {
        if(!incomingPermissions){
            return false
        }
        const mixedMenuItems = menuItems?.map((menuItem) => {
            const matchingApiMenu = incomingPermissions?.find(
                (menu) => menu.SubFeatureName === menuItem.SubFeatureName
            );
            
            if(!matchingApiMenu) return null
            return {
                ...menuItem,
                Permission_Id: matchingApiMenu ? `${matchingApiMenu?.Permission_Id}` : `${permissionTypes[2].key}`,
            };
        }).filter(item => item?.Menu_Name)
        if(mixedMenuItems?.length === 0) {
            setPermissions([]);
            localStorage.setItem('permissions', JSON.stringify([]));
            localStorage.setItem('user', JSON.stringify([]));
            return;
        }
        const filteredSubMenuItems = mixedMenuItems?.filter(item => item.Menu_Name !== item.SubFeatureName);
        const mainMenuItems = mixedMenuItems?.filter(item => item.Menu_Name === item.SubFeatureName);
        const filteredMenuItems = mainMenuItems?.map(item => ({
                ...item,
                ShowInMenu: item.Path === "/user-profile" ? false : ((item.ShowInMenu && item.Permission_Id === `${permissionTypes[1].key}`) || item.Permission_Id === `${permissionTypes[0].key}`)
            }));
        const checkForSubMenu = filteredSubMenuItems?.some(item => item.Permission_Id === `${permissionTypes[1].key}` || item.Permission_Id === `${permissionTypes[0].key}`)
        const subMenuArray = filteredSubMenuItems?.length > 0 ? { MenuName : filteredSubMenuItems[0].Menu_Name, Icon: '', IsSubMenu : true, ShowInMenu: checkForSubMenu,   SubMenuItems: filteredSubMenuItems, } : {};
        const permittedMenuItems = [ ...filteredMenuItems, subMenuArray ];
        setPermissions(permittedMenuItems)
        localStorage.setItem('permissions', JSON.stringify(permittedMenuItems));
        return permittedMenuItems
    };

    const logout = () => {
        setUser(null);
        localStorage.removeItem('user');
        localStorage.removeItem('permissions');
    };

    const contextValue = useMemo(() => ({ user, permissions, login, logout, setUserPermissions, openRoleChangedPopup, setOpenRoleChangedPopup }), [user, permissions, openRoleChangedPopup]);

    return (
        <UserContext.Provider value={contextValue}>
            {children}
        </UserContext.Provider>
    );
}

UserProvider.propTypes = {
    children: PropTypes.node.isRequired
};


export const useUser = () => useContext(UserContext);
