import { useEffect, useMemo, useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import isNil from 'lodash/isNil';

import type { AxiosError } from 'axios';
import { BlockletSDK } from '@blocklet/js-sdk';
import Toast from '../Toast';
import { formatAxiosError } from '../Util';
import type { User } from './types';

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

  const userDid = useMemo(() => user?.did, [user]);

  // 判断 user 对象中 isFollowing 值是否有效，有isFollowed字段并且值不为 undefined 或 null
  // 如果为 true 则不需要通过 api 查询，直接使用 user.isFollowing 值
  // 如果为 false 则需要通过 api 查询，并设置 user.isFollowing 值
  const hasFollowedField = useMemo(() => {
    return Object.prototype.hasOwnProperty.call(user, 'isFollowing') && !isNil((user as any).isFollowing);
  }, [user]);

  const client = useMemo(() => {
    let _client: BlockletSDK | null = null;
    try {
      _client = new BlockletSDK();
    } catch (error) {
      console.error('Failed to initialize BlockletSDK:', error);
      _client = null;
    }
    return _client;
  }, []);

  const isFollowingUser = useMemoizedFn(async () => {
    if (!client) {
      setFollowed(false);
      return;
    }
    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 (!client || (isMySelf && followUserDid === userDid)) {
      return;
    }
    try {
      await client.user.followUser({ userDid: followUserDid });
      Toast.success(t('follow_success'));
      isFollowingUser();
    } catch (error) {
      console.error(error);
      Toast.error(formatAxiosError(error as AxiosError));
    }
  });
  const unfollowUser = useMemoizedFn(async (unfollowUserDid: string = userDid) => {
    if (!client || (isMySelf && unfollowUserDid === userDid)) {
      return;
    }
    try {
      await client.user.unfollowUser({ userDid: unfollowUserDid });
      Toast.success(t('unfollow_success'));
      isFollowingUser();
    } catch (error) {
      console.error(error);
      Toast.error(formatAxiosError(error as AxiosError));
    }
  });

  useEffect(() => {
    // 如果 user 对象中已经存在了 isFollowing 字段，则不进行查询
    if (visible && userDid && !isMySelf && !!client && !hasFollowedField) {
      isFollowingUser();
    }
  }, [isFollowingUser, userDid, isMySelf, client, hasFollowedField, visible]);

  // 如果 user 对象中已经存在了 isFollowing 字段，则直接设置 followed 状态
  useEffect(() => {
    if (hasFollowedField) {
      setFollowed((user as any)?.isFollowing || false);
    }
  }, [hasFollowedField, user]);

  return {
    followed,
    followUser,
    unfollowUser,
  };
}
