import V2NIM from "nim-web-sdk-ng";
import { V2NIMUser } from "nim-web-sdk-ng/dist/v2/NIM_BROWSER_SDK/V2NIMUserService";
import { createContext, useCallback, useEffect } from "react";
import { userListAtom } from "@/atoms/im";
import { useAtom, useSetAtom } from "jotai";

const NimUserContext = createContext({
  getUserInfos: (accountIds: string[]) => {},
});

export const NimUserProvider = ({ children, nim }: { children: React.ReactNode, nim: V2NIM }) => {
  const [userList, setUserList] = useAtom(userListAtom);

  useEffect(() => {
    const handleUserInfoChanged = (users: V2NIMUser[]) => {
      console.log('handleUserInfoChanged', users);
      addUser(users);
    }

    nim.V2NIMUserService.on("onUserProfileChanged", handleUserInfoChanged)
    return () => {
      nim.V2NIMUserService.off("onUserProfileChanged", handleUserInfoChanged)
    }
  }, [nim.V2NIMUserService])

  const addUser = useCallback((users: V2NIMUser[]) => {
    users
      .filter(user => !!user.accountId)
      .forEach(user => {
        setUserList(prev => {
          const newUserList = new Map(prev);
          newUserList.set(user.accountId, user);
          return newUserList;
        });
    });
  }, [setUserList]);


  const getUserInfos = useCallback(async (accountIds: string[]) => {
    const existUserIds = Array.from(userList.keys());
    const newUserIds = accountIds.filter(id => !existUserIds.includes(id));
    console.log('getUserInfos 获取用户信息:', { newUserIds });
    const users = await nim.V2NIMUserService.getUserList(newUserIds)
    console.log('getUserInfos 获取用户信息:', { users });
    addUser(users);
  }, [nim.V2NIMUserService]);
  
  const removeUsers = useCallback((accountIds: string[]) => {
    setUserList(prev => {
      accountIds.forEach(accountId => {
        prev.delete(accountId);
      });
      return prev;
    });
  }, [setUserList]);

  return (
    <NimUserContext.Provider value={{ getUserInfos }}>
      {children}
    </NimUserContext.Provider>
  );
}
 
export default NimUserContext;