import { useEffect, useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import Toast from '@arcblock/ux/lib/Toast';

import type { AxiosError } from 'axios';
import { client } from '../libs/client';
import { formatAxiosError } from '../UserCenter/libs/utils';

/**
 * 登录用户与当前用户（userDid）的关注关系
 */
export default function useFollow({
  userDid,
  t,
  isMySelf,
}: {
  userDid: string;
  t: (k: string) => string;
  isMySelf: boolean;
}) {
  const [followed, setFollowed] = useState(false);

  const isFollowingUser = useMemoizedFn(async () => {
    try {
      if (isMySelf) {
        setFollowed(true);
        return;
      }
      const res = await client.user.isFollowingUser({ userDid });
      setFollowed(res);
    } catch (error) {
      console.error(error);
    }
  });

  const followUser = useMemoizedFn(async (followUserDid: string = userDid) => {
    if (isMySelf && followUserDid === userDid) {
      return;
    }
    try {
      await client.user.followUser({ userDid: followUserDid });
      Toast.success(t('profile.follow_success'));
      isFollowingUser();
    } catch (error) {
      console.error(error);
      Toast.error(formatAxiosError(error as AxiosError));
    }
  });
  const unfollowUser = useMemoizedFn(async (unfollowUserDid: string = userDid) => {
    if (isMySelf && unfollowUserDid === userDid) {
      return;
    }
    try {
      await client.user.unfollowUser({ userDid: unfollowUserDid });
      Toast.success(t('profile.unfollow_success'));
      isFollowingUser();
    } catch (error) {
      console.error(error);
      Toast.error(formatAxiosError(error as AxiosError));
    }
  });

  useEffect(() => {
    if (userDid && !isMySelf) {
      isFollowingUser();
    }
  }, [isFollowingUser, userDid, isMySelf]);

  return {
    followed,
    followUser,
    unfollowUser,
  };
}
