import { useState as y, useMemo as f, useEffect as d } from "react";
import { useMemoizedFn as w } from "ahooks";
import U from "lodash/isNil";
import { BlockletSDK as x } from "@blocklet/js-sdk";
import u from "../Toast/index.js";
const F = (r) => {
  const { response: t } = r;
  return t ? `Request failed: ${t.status} ${t.statusText}: ${JSON.stringify(t.data)}` : r.message;
};
function z({
  user: r,
  t,
  isMySelf: n,
  visible: m
}) {
  const [p, c] = y(!1), s = f(() => r?.did, [r]), i = f(() => Object.prototype.hasOwnProperty.call(r, "isFollowing") && !U(r.isFollowing), [r]), e = f(() => {
    let o = null;
    try {
      o = new x();
    } catch (l) {
      console.error("Failed to initialize BlockletSDK:", l), o = null;
    }
    return o;
  }, []), a = w(async () => {
    if (!e) {
      c(!1);
      return;
    }
    try {
      if (n) {
        c(!0);
        return;
      }
      const o = await e.user.isFollowingUser({ userDid: s });
      c(o);
    } catch (o) {
      console.error(o);
    }
  }), g = w(async (o = s) => {
    if (!(!e || n && o === s))
      try {
        await e.user.followUser({ userDid: o }), u.success(t("follow_success")), a();
      } catch (l) {
        console.error(l), u.error(F(l));
      }
  }), h = w(async (o = s) => {
    if (!(!e || n && o === s))
      try {
        await e.user.unfollowUser({ userDid: o }), u.success(t("unfollow_success")), a();
      } catch (l) {
        console.error(l), u.error(F(l));
      }
  });
  return d(() => {
    m && s && !n && e && !i && a();
  }, [a, s, n, e, i, m]), d(() => {
    i && c(r?.isFollowing || !1);
  }, [i, r]), {
    followed: p,
    followUser: g,
    unfollowUser: h
  };
}
export {
  z as default,
  F as formatAxiosError
};
