/* eslint-disable no-param-reassign */
/* eslint-disable react/no-array-index-key */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import "../../css/user.css";
import "../../css/user_no_container.css";

import { Drawer, Popover, Typography } from "antd";
import { BigNumber } from "bignumber.js";
import classNames from "classnames";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { ReactSVG } from "react-svg";
import { useAccount, useDisconnect } from "wagmi";

import ArrowDown from "../../assets/icons/arrow-down.svg";
import ExitIcon from "../../assets/icons/exit.svg";
import { BASE_URL, NODE_REAL_CHAIN } from "../config";
import { handleGetImageUrl, isMobile, isNft, isProbablyEVMAddress, truncateAddress } from "../utils";
import FontIcon from "./FontIcon";
import Icon from "./Icon";
import { MyAvatar } from "./MyAvatar";

const { Paragraph } = Typography;
type LinkType = {
  faceUrl?: string;
  defaultIcon: string;
  des: string;
  link: string;
  defaultUrl: string;
  bgc: string;
  linkName: string;
  type: string;
  showStatus: number;
};
type AssetsType = {
  contract_decimals: number;
  contract_name: string;
  contract_ticker_symbol: string;
  contract_address: string;
  supports_erc: string[];
  logo_url: string;
  last_transferred_at: string;
  native_token: boolean;
  type: string;
  balance: string;
  balance_24h: string;
  quote_rate: number;
  quote_rate_24h: number;
  quote: number;
  quote_24h: number;
  nft_data: null;
  chain_id: number;
};
type UserInfoType = {
  hasNewMsg?: boolean;
  dnsDomain?: string;
  emailAddress?: string;
  faceURL?: string;
  isShowBalance?: boolean;
  isShowEmail?: boolean;
  dnsDomainVerify?: number;
  isShowTwitter?: boolean;
  nftListShow?: [];
  nickname?: string;
  openAnnouncement?: number;
  operationID?: string;
  tokenContractChain?: string;
  userHeadTokenInfo?: {
    ID?: number;
    isLikes?: number;
    likesCount?: number;
    nftChainID?: string;
    nftContract?: string;
    nftContractType?: string;
    nftTokenURL?: string;
    tokenID?: string;
  };
  userID?: string;
  userIntroduction?: string;
  userProfile?: string;
  userTwitter?: string;
  linkTree?: LinkType[];
  followingCount?: number;
  followsCount?: number;
};

function PopContent(props: { userInfo: UserInfoType; totalAssets: number }) {
  const { userInfo, totalAssets } = props;
  const { disconnect } = useDisconnect();
  const [t] = useTranslation();
  return (
    <div className="w3a-user-card">
      <div className="w3a-user-info">
        <MyAvatar isNft={isNft(userInfo?.tokenContractChain)} shape="circle" src={handleGetImageUrl(userInfo?.faceURL)} size={88} />
        {!isProbablyEVMAddress(userInfo?.nickname) && <p className="w3a-user-nickname">{truncateAddress(userInfo?.nickname)}</p>}
        <Paragraph
          className={classNames("w3a-user-userid", isProbablyEVMAddress(userInfo?.nickname) ? "w3a-user-userid-max" : "")}
          copyable={{
            text: userInfo?.userID,
            icon: <Icon style={{ marginLeft: "3px" }} width="12px" height="12px" iconName="copy" />,
          }}
        >
          {truncateAddress(userInfo?.userID)}
        </Paragraph>
        <Paragraph className="w3a-user-intro" ellipsis={{ rows: 2 }}>
          {userInfo?.userIntroduction}
        </Paragraph>
      </div>
      <div className="w3a-user-profile">
        <div className="w3a-profile-item">
          <span className="w3a-profile-title">Followers</span>
          <span className="w3a-profile-value">{userInfo?.followingCount ?? 0}</span>
        </div>
        <div className="w3a-profile-item">
          <span className="w3a-profile-title">Following</span>
          <span className="w3a-profile-value">{userInfo?.followsCount ?? 0}</span>
        </div>
        <div className="w3a-profile-item">
          <span className="w3a-profile-title">Net Worth</span>
          <span className="w3a-profile-value">${totalAssets.toFixed(2)}</span>
        </div>
      </div>
      {userInfo?.linkTree && userInfo?.linkTree?.length > 0 && (
        <div className="w3a-socials">
          {userInfo?.linkTree
            .filter((el) => el.type === "normal")
            ?.map((i, idx) => (
              <span onClick={() => window.open(i.link)} className="w3a-social-item" key={idx}>
                {i.faceUrl ? <img src={i.faceUrl} alt="" /> : <FontIcon type={i.defaultIcon} color="#fff" size={24} />}
              </span>
            ))}
        </div>
      )}

      <div className="w3a-wallet-action">
        <div onClick={() => disconnect()} className="w3a-wallet-btn">
          <ReactSVG className="w3a-wallet-exit-icon" color="#fff" src={ExitIcon} />
          {t("modal.public.logout")}
        </div>
      </div>
    </div>
  );
}

export function ConnectButton() {
  const { address } = useAccount();
  const [userInfo, setUserInfo] = useState<UserInfoType | null>(null);
  const [open, setOpen] = useState<boolean>(false);
  const [userAssets, setUserAssets] = useState<number>(0);
  const fetchUserInfo = async () => {
    const res = await fetch(`${BASE_URL}/user/get_user_setting_page`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        userID: address.toLocaleLowerCase(),
        operationID: `${Date.now()}`,
      }),
    });

    if (res.ok) {
      const userInfoData = await res.json();
      setUserInfo(userInfoData.data);
    }
  };

  const fetchUserAssets = async (chainNet: number, userID: string) => {
    const res = await fetch(`${BASE_URL}/nft/get_show_balance`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        chainNet: NODE_REAL_CHAIN[chainNet],
        userID,
        operationID: `${Date.now()}`,
      }),
    });
    return res.json();
  };
  const calcluateUserAssets = async (userID: string) => {
    if (!userID) {
      setUserAssets(0);
      return;
    }
    const res1 = await fetchUserAssets(1, userID);
    const res2 = await fetchUserAssets(56, userID);
    const res3 = await fetchUserAssets(137, userID);
    let list = [];
    let list1: AssetsType[] = [];
    let list2: AssetsType[] = [];
    let list3: AssetsType[] = [];
    if (res1) {
      list1 = res1?.data?.items.map((i) => {
        i.chain_id = res1.chain_id;
        return i;
      });
      list1 = res1?.data?.items.filter((i) => i.contract_name !== "");
    }
    if (res2) {
      list2 = res2?.data?.items.map((i) => {
        i.chain_id = res2.chain_id;
        return i;
      });
      list2 = res2?.data?.items.filter((i) => i.contract_name !== "");
    }
    if (res3) {
      list3 = res3?.data?.items.map((i) => {
        i.chain_id = res3.chain_id;
        return i;
      });
      list3 = res3?.data?.items.filter((i) => i.contract_name !== "");
    }
    list = [...list3, ...list2, ...list1];
    const total = list.reduce((acc, item) => {
      const balance = new BigNumber(item.balance)
        .div(10 ** item.contract_decimals)
        .times(item.quote_rate)
        .toNumber();
      return acc + balance;
    }, 0);
    setUserAssets(total);
  };
  useEffect(() => {
    if (address) {
      fetchUserInfo();
      calcluateUserAssets(address);
    }
  }, [address]);

  return (
    <div className="w3a-parent-container">
      {isMobile() ? (
        <>
          <div
            onClick={() => {
              setOpen(true);
            }}
            className="w3a-user-info"
          >
            <MyAvatar isNft={isNft(userInfo?.tokenContractChain)} shape="circle" src={handleGetImageUrl(userInfo?.faceURL)} size={40} />
            <span className="w3a-user-nickname">{truncateAddress(userInfo?.nickname)}</span>
            <ReactSVG style={{ rotate: open ? "180deg" : "0deg" }} className="w3a-arrow-down-icon" src={ArrowDown} />
          </div>
          <Drawer
            rootClassName="w3a-parent-container ui_drawer"
            open={open}
            placement="left"
            onClose={() => {
              setOpen(false);
            }}
            closable={false}
            key="left"
            bodyStyle={{
              minHeight: "50vh",
            }}
          >
            <div
              onClick={() => {
                setOpen(false);
              }}
              className="class_btn"
            >
              <FontIcon size={11} type="icon-danchuangguanbi" />
            </div>
            <PopContent totalAssets={userAssets} userInfo={userInfo} />
          </Drawer>
        </>
      ) : (
        <div className="w3a-user-wrap">
          <Popover
            style={{ width: "350px" }}
            rootClassName="w3a-parent-container"
            arrow={false}
            open={open}
            placement="bottomRight"
            onOpenChange={(val) => setOpen(val)}
            trigger="click"
            content={<PopContent totalAssets={userAssets} userInfo={userInfo} />}
          >
            <div className="w3a-user-info">
              <MyAvatar isNft={isNft(userInfo?.tokenContractChain)} shape="circle" src={handleGetImageUrl(userInfo?.faceURL)} size={40} />
              <span className="w3a-user-nickname">{truncateAddress(userInfo?.nickname)}</span>
              <ReactSVG className="w3a-arrow-down-icon" src={ArrowDown} />
            </div>
          </Popover>
        </div>
      )}
    </div>
  );
}
