"use client";
import React, { useState, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import { setCookie, getCookie } from "cookies-next";
import { useRouter } from "next/navigation";
import baseRequest from "@/utils/baseRequest";
import { Toast } from "antd-mobile";
import { generateSignature } from "@/utils/crypto";

export default function WithDrawal() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const mid = searchParams.get("mid");
  const token = searchParams.get("token");
  const mobile_phone = searchParams.get("mobile_phone");

  //将searchParams中的mid和token写入cookie，并重定向到没有searchParams的路由
  useEffect(() => {
    if (mid && token && mobile_phone) {
      setCookie("mid", mid);
      setCookie("token", token);
      setCookie("mobile_phone", mobile_phone);
      router.replace("/withdrawal");
    }
  }, [mid, token, mobile_phone]);

  //查看主播实名认证情况和可提现数额
  const [data, setData] = useState({});
  useEffect(() => {
    const getData = async () => {
      const mid = getCookie("mid");
      if (!mid) return;
      try {
        const base = baseRequest();
        const body = {
          ...base,
        };
        const signature = generateSignature(body);
        const verificationResponse = await fetch(
          `/api/hvyogo/query_agree_state?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(body),
          }
        );
        const verificationData = await verificationResponse.json();
        console.log(verificationData);
        if (verificationData.ret === -1) {
          Toast.show({
            content: verificationData.msg,
          });
        }
        const signature2 = generateSignature({
          ...base,
        });
        const withdrawalResponse = await fetch(
          `/api/vas/withdraw_page?signature=${signature2}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              ...base,
            }),
          }
        );
        const withdrawalData = await withdrawalResponse.json();
        if (withdrawalData.ret === -1) {
          Toast.show({
            content: withdrawalData.msg,
          });
          return;
        }
        setData({
          verificationStatus: verificationData.data?.agree_state,
          withdrawal_diamond: withdrawalData.data.withdraw_diamonds,
        });
      } catch (error) {
        console.error(error);
      }
    };
    getData();
  }, []);

  //跳转实名认证
  const handleVerify = () => {
    const token = getCookie("token");
    const huiYongGongUrl = `http://bh5-channel.hvyogo.com/?channel=CDLX&token=${token}`;
    router.push(huiYongGongUrl);
  };

  return (
    <section className="container flex flex-col flex-1 p-4">
      <div className="flex flex-row justify-between items-center bg-[#FFFFFF1A] rounded-2xl p-4">
        <p className="text-secondary text-base font-medium">
          可提现钻石：
          <span className="text-white text-xl font-medium">
            {data?.withdrawal_diamond}
          </span>
        </p>
        {data?.verificationStatus === 2 ? (
          <button
            onClick={() => router.push("/withdrawal/checkout")}
            className="btn btn-sm btn-primary text-white rounded-full"
          >
            提现
          </button>
        ) : (
          <button
            onClick={handleVerify}
            className="btn btn-sm btn-primary text-white rounded-full"
          >
            实名认证
          </button>
        )}
      </div>
      <div className="flex flex-row justify-between items-center bg-[#FFFFFF1A] rounded-2xl p-4 my-4">
        <p className="text-secondary text-base font-medium">
          钻石总额：
          <span className="text-white text-xl font-medium">20000</span>
        </p>
      </div>
      <p className="text-secondary text-base mt-2">注意事项：</p>
      <p className="text-secondary text-sm">
        1.需实名认证并绑定收款方式后方可提现；
      </p>
      <p className="text-secondary text-sm">
        2.平台将收取提现金额的3%作为提现手续费用，该笔费用将用于为收款人缴纳相关税费；
      </p>
      <p className="text-secondary text-sm">
        3.收款账户需与实名认证本人保持一致；
      </p>
      <p className="text-secondary text-sm">
        4.单笔最低提现金额为100元（即1,000钻石），单月最高提现金额为95,000元（即950,000钻石）；
      </p>
      <p className="text-secondary text-sm">
        5.自助提现渠道每日只能提现一次，若有更多提现需求，请联系客服。
      </p>
    </section>
  );
}
