"use client";

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

export default function Recharge() {
  const router = useRouter();

  //用户user_id
  const [userId, setUserId] = useState("");

  //商品列表
  const [productList, setProductList] = useState([]);

  //选择的价格档位
  const [selectedPrice, setSelectedPrice] = useState({});

  //选择任意金额充值
  const [customCoin, setCustomCoin] = useState({ selected: false, num: 1000 });

  //查询用户信息
  const [selectedUser, setSelectedUser] = useState({});
  const querryUserData = async () => {
    const base = baseRequest();
    const body = { ...base, user_id: parseInt(userId, 10) };
    const signature = generateSignature(body);
    try {
      const response = await fetch(
        `/api/account/list_others_by_user_id?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const data = await response.json();
      console.log(data);
      if (data.ret === -1) {
        Toast.show({
          content: data.msg,
        });
        return;
      }
    } catch (error) {
      console.error(error);
    }
  };

  //任意金额充值的金币数量
  const handleChangeCustomCoin = (e) => {
    let newValue = parseInt(e.target.value, 10);
    // 确保输入的值在最小值和最大值范围内
    if (newValue >= 0 && newValue <= 100000) {
      setCustomCoin({ ...customCoin, num: newValue });
    } else if (isNaN(newValue)) {
      setCustomCoin({ ...customCoin, num: 0 });
    } else if (newValue > 100000) {
      setCustomCoin({ ...customCoin, num: 100000 });
    }
  };

  //获取当前充值档位
  const [isFetching, setIsFetching] = useState(true);
  useEffect(() => {
    const getData = async () => {
      const base = baseRequest();
      const body = { ...base };
      const signature = generateSignature(body);
      try {
        const response = await fetch(
          `/api/vas/get_coins_product_list?signature=${signature}`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(body),
          }
        );
        const data = await response.json();
        if (data.ret === -1) {
          Toast.show({
            content: data.msg,
          });
          return;
        }
        setProductList(data.data.list_alipay_h5);
        setIsFetching(false);
      } catch (error) {
        console.error(error);
      }
    };
    getData();
  }, []);

  //创建充值订单
  const [isLoading, setIsLoading] = useState(false);
  const createOrder = async (type = "alipay_h5") => {
    if (!selectedPrice.id && !customCoin.selected) {
      Toast.show({
        content: "请选择充值档位",
      });
      return;
    }
    if (customCoin.selected && customCoin.num < 10) {
      Toast.show({
        content: "最低充值1元哦～",
      });
      return;
    }

    const base = baseRequest();
    const body = {
      ...base,
      product_id: customCoin.selected ? "h5_custom_coin" : selectedPrice.id,
      custom_coins: customCoin.selected ? customCoin.num : 0,
      pay_type: type,
      from: "app",
    };

    //如果是微信jsapi支付直接跳转到中间页
    if (type === "wxpay_jsapi") {
      router.push(`/pay/${encodeURIComponent(JSON.stringify(body))}`);
      return;
    }

    setIsLoading(true);

    const signature = generateSignature(body);
    try {
      const response = await fetch(
        `/api/vas/create_order?signature=${signature}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        }
      );
      const data = await response.json();
      if (data.ret === -1) {
        Toast.show({
          content: data.msg,
        });
        return;
      }
      switch (type) {
        case "alipay_h5":
          router.push(`${data.data.alipay_h5_param_str}`);
          break;
        case "wxpay_h5":
          router.push(
            `https://shop.tiefen.fun/pay/wxpay_h5/${encodeURIComponent(
              data.data.wxpay_h5_param_str
            )}`
          );
          break;
        default:
          router.push(`${data.data.alipay_h5_param_str}`);
          break;
      }
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  const PriceItem = ({ item }) => {
    const handleClickPrice = (item) => {
      setSelectedPrice(item);
      setCustomCoin({ ...customCoin, selected: false });
    };
    return (
      <div className="basis-1/3 p-2">
        <button
          onClick={() => handleClickPrice(item)}
          className={
            selectedPrice.id === item.id
              ? "flex flex-col w-full py-4 border bg-[#FF61B030] border-primary rounded-lg items-center"
              : "flex flex-col w-full py-4 border bg-[#FFFFFF1A] border-secondary rounded-lg items-center"
          }
        >
          <p
            className={
              selectedPrice.id === item.id
                ? "text-base text-primary"
                : "text-base text-secondary"
            }
          >
            {item.name}
          </p>
          <p
            className={
              selectedPrice.real_price === item.real_price
                ? "text-base text-primary"
                : "text-base text-secondary"
            }
          >
            ¥{item.real_price / 100}
          </p>
        </button>
      </div>
    );
  };

  if (isFetching) {
    return (
      <section className="flex flex-1 justify-center container">
        <span className="absolute top-1/2 loading loading-spinner loading-lg"></span>
      </section>
    );
  }

  return (
    <section className="flex flex-1 justify-center container">
      {isLoading && (
        <span className="absolute top-1/2 loading loading-spinner loading-lg"></span>
      )}
      <div className="flex flex-1 flex-col p-4">
        <p className="text-white text-base font-semibold my-2">
          请选择您要充值的账号
        </p>
        <div className="flex flex-row">
          <input
            type="text"
            name="user_id"
            placeholder="请输入您的用户ID"
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
            className="input input-bordered input-md input-primary w-full"
          />
          <button
            onClick={querryUserData}
            className="btn btn-primary text-white max-w-sm ml-2"
          >
            搜索
          </button>
        </div>
        {/* <div className="flex flex-row justify-between items-center py-2 border-b-2 border-neutral">
        <div className="flex flex-row items-center">
          <img
            className="w-12 h-12 rounded-full"
            src={item.account?.avatar?.images[0].urls[0]}
            alt=""
          />
          <div className="flex flex-col ml-2">
            <p className="text-base text-white font-medium">
              {item.account?.name}
            </p>
            <p className="text-sm text-secondary font-medium">{orderLabel}</p>
          </div>
        </div>
        {item.lock_type === 0 && item.order_status !== 6 && (
          <button
            className="btn btn-sm btn-primary text-white rounded-full"
            onClick={handleClick}
          >
            查看微信
          </button>
        )}
      </div> */}
        <p className="text-white text-base font-semibold my-2">选择充值金额</p>
        <div className="flex flex-wrap">
          {productList?.map((item) => (
            <PriceItem key={item.id} item={item} />
          ))}
          {/* 任意金额充值 */}
          <div className="basis-1/3 p-2">
            <button
              onClick={() => {
                setSelectedPrice([]);
                setCustomCoin({ ...customCoin, selected: true });
              }}
              className={
                customCoin.selected
                  ? "flex flex-col w-full h-full py-4 border bg-[#FF61B030] border-primary rounded-lg items-center justify-center"
                  : "flex flex-col w-full h-full py-4 border bg-[#FFFFFF1A] border-secondary rounded-lg items-center justify-center"
              }
            >
              <p
                className={
                  customCoin.selected
                    ? "text-base text-primary"
                    : "text-base text-secondary"
                }
              >
                自定义金币
              </p>
            </button>
          </div>
        </div>
        {customCoin.selected && (
          <div className="px-2 mt-2">
            <input
              type="number"
              name="custom_price"
              placeholder="请输入金币数额"
              value={customCoin.num.toString()}
              onChange={handleChangeCustomCoin}
              className="input input-bordered input-md input-primary w-full"
            />
            <p className="text-secondary text-base mt-2">
              预估金额：¥{customCoin.num / 10}
            </p>
          </div>
        )}
        <div className="flex mt-auto mb-12">
          <div className="w-full px-2">
            <button
              onClick={() => createOrder("alipay_h5")}
              className="flex flex-row h-12 w-full items-center justify-center bg-primary rounded-full py-2"
            >
              <svg viewBox="0 0 1024 1024" width="18" height="18">
                <path
                  d="M1024.0512 701.0304V196.864A196.9664 196.9664 0 0 0 827.136 0H196.864A196.9664 196.9664 0 0 0 0 196.864v630.272A196.9152 196.9152 0 0 0 196.864 1024h630.272a197.12 197.12 0 0 0 193.8432-162.0992c-52.224-22.6304-278.528-120.32-396.4416-176.64-89.7024 108.6976-183.7056 173.9264-325.3248 173.9264s-236.1856-87.2448-224.8192-194.048c7.4752-70.0416 55.552-184.576 264.2944-164.9664 110.08 10.3424 160.4096 30.8736 250.1632 60.5184 23.1936-42.5984 42.496-89.4464 57.1392-139.264H248.064v-39.424h196.9152V311.1424H204.8V267.776h240.128V165.632s2.1504-15.9744 19.8144-15.9744h98.4576V267.776h256v43.4176h-256V381.952h208.8448a805.9904 805.9904 0 0 1-84.8384 212.6848c60.672 22.016 336.7936 106.3936 336.7936 106.3936zM283.5456 791.6032c-149.6576 0-173.312-94.464-165.376-133.9392 7.8336-39.3216 51.2-90.624 134.4-90.624 95.5904 0 181.248 24.4736 284.0576 74.5472-72.192 94.0032-160.9216 150.016-253.0816 150.016z"
                  fill="#FFFFFF"
                ></path>
              </svg>
              <p className="text-white text-base ml-1">支付宝</p>
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}
