import { createContext, useContext } from 'react';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useMemoizedFn } from 'ahooks';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';

import useFollow from '../hooks/use-follow';
import { translations } from '../UserCenter/libs/locales';

const UserFollowersContext = createContext<UserFollowersContextType>({
  followed: false,
  followUser: () => {},
  unfollowUser: () => {},
});
const { Provider } = UserFollowersContext;

type UserFollowersContextType = {
  followed: boolean;
  followUser: () => void;
  unfollowUser: () => void;
};

function UserFollowersProvider({
  isMySelf,
  userDid,
  children,
}: {
  children: React.ReactNode;
  isMySelf: boolean;
  userDid: string;
}) {
  const { locale } = useLocaleContext();
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const { followed, followUser, unfollowUser } = useFollow({ userDid, t, isMySelf });

  return (
    <Provider
      value={{
        followed,
        followUser,
        unfollowUser,
      }}>
      {children}
    </Provider>
  );
}

function useUserFollowersContext() {
  const res = useContext(UserFollowersContext);
  return res;
}

export { UserFollowersContext, useUserFollowersContext, UserFollowersProvider };
