"use client";

import React, { useEffect, useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faAngleRight } from "@fortawesome/free-solid-svg-icons";
import { Avatar, Toast, Space } from "antd-mobile";
import { useRouter } from "next/navigation";
import { get } from "@/utils/storeInfo";
import requireAPI from "@/utils/requireAPI";
import OwnIcon from "@/components/OwnIcon";
import OwnImage from "@/components/OwnImage";
const My = () => {
  const [userInfo, setUserInfo] = useState({});
  const router = useRouter();
  const [streamerNavigates, setStreamerNavigates] = useState([]);
  const [userNavigates, setUserNavigates] = useState([]);
  useEffect(() => {
    const userInfo = get("account");
    if (userInfo) {
      getData(userInfo);
    }
  }, []);
  const getData = async (oldUserInfo) => {
    const data = await requireAPI(
      "POST",
      "/api/account_relation/count",
      null,
      true
    );
    if (data.ret === -1) {
      Toast.show({
        icon: "fail",
        content: data.msg,
        position: "top",
      });
      return;
    }
    const streamer = await requireAPI(
      "POST",
      "/api/streamer/list_ext_by_mid",
      null,
      true
    );
    if (streamer.ret === -1) {
      Toast.show({
        icon: "fail",
        content: streamer.msg,
        position: "top",
      });
      return;
    }
    const account = await requireAPI(
      "POST",
      "/api/account/list_by_mid",
      null,
      true
    );
    if (account.ret === -1) {
      Toast.show({
        icon: "fail",
        content: account.msg,
        position: "top",
      });
      return;
    }
    const statuses = await requireAPI(
      "POST",
      "/api/streamer_auth_approval/get_statuses",
      null
    );
    if (statuses.ret === -1) {
      Toast.show({
        icon: "fail",
        content: statuses.msg,
        position: "top",
      });
      return;
    }
    const isInJoinProgress =
      (statuses.data.basic_status === 0 ||
        statuses.data.basic_status === 1 ||
        statuses.data.basic_status === 3) &&
      statuses.data.details_status !== 1;
    setStreamerNavigates((old) => {
      if (account.data.account.role == 3 || isInJoinProgress) {
        const zoneLength = streamer.data?.streamer_ext?.zones?.length;
        let currentOld = [
          {
            url: !zoneLength
              ? `my/createProfile`
              : `space/${account.data.account.mid}`,
            iconUrl: `/icons/32DP/space.png`,
            title: !zoneLength ? "开通空间" : "我的空间",
            subTitle:
              account.data.account.role == 3 ? "创作者功能" : "完善资料后解锁",
          },
          {
            url: `streamerPosts/${account.data.account.mid}`,
            iconUrl: "/icons/32DP/myposts.png",
            title: "广场动态",
            subTitle:
              account.data.account.role == 3 ? "创作者功能" : "完善资料后解锁",
          },
          {
            url: `my/wechatWaitingToAdd`,
            iconUrl: "/icons/32DP/wechat.png",
            title: "待添加微信",
            subTitle:
              account.data.account.role == 3 ? "创作者功能" : "完善资料后解锁",
          },
          {
            url: `my/editprofile`,
            iconUrl: "/icons/32DP/editprofile.png",
            title: "编辑资料",
            subTitle:
              account.data.account.role == 3 ? "创作者功能" : "完善资料后解锁",
          },
          {
            url: `my/refund/refundList`,
            iconUrl: "/icons/32DP/wallet.png",
            title: "退款审核",
            subTitle:
              account.data.account.role == 3 ? "创作者功能" : "完善资料后解锁",
          },
          // ...currentOld,
        ];
        if (isInJoinProgress) {
          currentOld = [
            {
              url: `my/streamerVerification/completeStreamerInformation`,
              iconUrl: "/icons/32DP/editprofile.png",
              title: "完善资料",
              subTitle: "完善后解锁全部功能",
              status:
                statuses.data.details_status == 0
                  ? "审核中"
                  : statuses.data.details_status == 2
                  ? "未通过"
                  : null,
              // disable: !isInJoinProgress,
            },
            ...currentOld,
          ];
        }
        return currentOld;
      }
      return old;
    });
    setUserNavigates((old) => {
      let currentOld = [
        {
          url: `my/wallet`,
          iconUrl: "/icons/32DP/wallet.png",
          title: "我的钱包",
        },
        {
          url: `my/unlockedWechat`,
          iconUrl: "/icons/32DP/wechat.png",
          title: "已解锁微信",
        },
        {
          url: `my/streamerVerification/joinEntrance`,
          iconUrl: "/icons/32DP/join.png",
          title: "申请入驻",
        },
        {
          url: `/messageDetail`,
          iconUrl: "/icons/32DP/contact.png",
          title: "联系客服",
        },
        {
          url: `/my/addToHome`,
          iconUrl: "/icons/32DP/toScreen.png",
          title: "添加到主屏幕",
        },
      ];
      // if (
      //   (account.data.account.role != 3 && !isInJoinProgress) ||
      //   statuses.data.details_status === 2
      // ) {
      //   currentOld = [
      //     {
      //       url: `my/wallet`,
      //       iconUrl: "icons/32DP/wallet.png",
      //       title: "我的钱包",
      //     },
      //     {
      //       url: `my/unlockedWechat`,
      //       iconUrl: "icons/32DP/wechat.png",
      //       title: "已解锁微信",
      //     },
      //     {
      //       url: `my/streamerVerification/joinEntrance`,
      //       iconUrl: "icons/32DP/join.png",
      //       title: "申请入驻",
      //     },
      //     {
      //       url: `/messageDetail`,
      //       iconUrl: "icons/32DP/contact.png",
      //       title: "联系客服",
      //     },
      //     {
      //       url: `/my/addToHome`,
      //       iconUrl: "icons/32DP/toScreen.png",
      //       title: "添加到主屏幕",
      //     },
      //   ];
      // }
      return currentOld;
    });
    setUserInfo({ ...data.data, ...account.data.account, ...streamer.data });
  };
  const ItemEle = ({
    url,
    iconUrl,
    title,
    subTitle,
    toWebView,
    status,
    disable,
  }) => {
    return (
      <li
        className="flex justify-between items-center p-3 py-2"
        onClick={() => {
          subTitle != "完善资料后解锁" &&
            !disable &&
            router.push(
              toWebView ? `/webView/${encodeURIComponent(url)}` : url
            );
        }}
      >
        <div className="flex items-center">
          <div className="mr-2">
            <OwnIcon className="w-[32px] h-[32px]" src={iconUrl} />
          </div>
          <span className="text-base">{title}</span>
        </div>
        <div className={`flex items-center text-[#FFFFFF80]`}>
          <div
            className={`rounded-full`}
            style={{
              backgroundColor: status
                ? status == "未通过"
                  ? "#db2020"
                  : "#207edb"
                : "none",
              padding: status ? "2px 10px" : "0",
              marginRight: !disable ? "0.5rem" : "0",
            }}
          >
            {status || subTitle}
          </div>
          {!disable && (
            <FontAwesomeIcon
              icon={faAngleRight}
              style={{ maxWidth: "12px" }}
              size="sm"
              className="h-4"
            />
          )}
        </div>
      </li>
    );
  };
  return (
    <div
      className={`p-4 pb-20 bg-no-repeat bg-contain bg-top`}
      style={{
        backgroundImage: `url(${
          process.env.NEXT_PUBLIC_WEB_ASSETS_URL +
          "/images/profilebackground.png"
        })`,
      }}
    >
      <div className="flex justify-end items-center z-10 w-full mb-4">
        <div
          className="w-9 h-9 flex items-center justify-center bg-[#FFFFFF1A] rounded-full mr-2"
          onClick={() =>
            router.push("my/editUserProfile/selectUserProfileItem")
          }
        >
          <OwnIcon
            src="/icons/32DP/edit.png"
            width={32}
            className="h-full w-full"
          />
        </div>
        <div
          className="w-9 h-9 flex items-center justify-center bg-[#FFFFFF1A] rounded-full"
          onClick={() => router.push("my/setting")}
        >
          <OwnIcon
            src="/icons/32DP/setting.png"
            width={32}
            className="h-full w-full"
          />
        </div>
      </div>
      {userInfo?.role === 3 ? (
        <div
          className="flex items-center justify-between mb-4"
          onClick={() => router.push("profile/" + userInfo.mid)}
        >
          <div className="flex items-center">
            <div className="mr-4">
              <OwnImage
                width="76px"
                height="76px"
                roundedFull
                src={userInfo.avatar?.images[0].urls[0]}
                className="rounded-full"
              />
            </div>
            <div>
              <Space align="center">
                <p
                  className={`text-2xl`}
                  style={{
                    color: userInfo?.is_a_member === 1 ? "#FFADBE" : "white",
                  }}
                >
                  {userInfo.name}
                </p>
                {userInfo?.is_a_member === 1 && (
                  <OwnIcon src="/icons/vipbig.png" width={32} height={32} />
                )}
              </Space>
              <div className="h-4 flex items-center text-xs bg-[#ffffff18] rounded-full px-2 py-2.5 mt-1 w-max">
                <OwnIcon
                  src="/icons/info/ID.png"
                  width={14}
                  height={14}
                  className="w-4 h-full mr-1"
                />
                <span>{userInfo.user_id}</span>
              </div>
            </div>
          </div>
          <FontAwesomeIcon
            icon={faAngleRight}
            style={{ maxWidth: "12px" }}
            size="xl"
            className="h-6 mr-2"
          />
        </div>
      ) : (
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center">
            <div className="mr-4">
              <OwnImage
                width="76px"
                height="76px"
                roundedFull
                src={userInfo.avatar?.images[0].urls[0]}
                className="rounded-full"
              />
            </div>
            <div>
              <Space align="center">
                <p
                  className={`text-2xl`}
                  style={{
                    color: userInfo?.is_a_member === 1 ? "#FFADBE" : "white",
                  }}
                >
                  {userInfo.name}
                </p>
                {userInfo?.is_a_member === 1 && (
                  <OwnIcon src="/icons/vipbig.png" width={32} height={32} />
                )}
              </Space>
              <div className="h-4 flex items-center text-xs bg-[#ffffff18] rounded-full px-2 py-2.5 mt-1 w-max">
                <OwnIcon
                  src="/icons/info/ID.png"
                  width={14}
                  height={14}
                  className="w-4 h-full mr-1"
                />
                <span>{userInfo.user_id}</span>
              </div>
            </div>
          </div>
        </div>
      )}
      <ul className="grid grid-cols-4 mb-4">
        <li
          className="text-center"
          onClick={() => router.push("my/relationship?key=follow")}
        >
          <p className="text-2xl">{userInfo?.follow_count || 0}</p>
          <p className="text-[#ffffff88]">关注</p>
        </li>
        <li
          className="text-center"
          onClick={() => router.push("my/relationship?key=fans")}
        >
          <p className="text-2xl">{userInfo?.is_followed_count || 0}</p>
          <p className="text-[#ffffff88]">粉丝</p>
        </li>
        <li className="text-center" onClick={() => router.push("my/wallet")}>
          <p className="text-2xl">{userInfo.gold_num || 0}</p>
          <p className="text-[#ffffff88]">金币</p>
        </li>
        <li className="text-center" onClick={() => router.push("my/wallet")}>
          <p className="text-2xl">{userInfo.diamond_num || 0}</p>
          <p className="text-[#ffffff88]">钻石</p>
        </li>
      </ul>

      {/* 主播用户 */}
      {!!streamerNavigates.length && (
        <div className="rounded-xl p-2 border-2 border-[#2c2b2f] mb-4">
          <ul>
            {streamerNavigates.map((item, index) => (
              <ItemEle key={index} {...item} />
            ))}
          </ul>
        </div>
      )}
      {/* 普通用户 */}
      {!!userNavigates.length && (
        <div className="rounded-xl p-2 border-2 border-[#2c2b2f]">
          <ul>
            {userNavigates.map((item, index) => (
              <ItemEle key={index} {...item} />
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

export default My;