"use client";

import React, { useState, useEffect, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import webviewBaseRequest from "@/utils/webviewBaseRequest";
import { Toast } from "antd-mobile";
import { InfiniteScroll } from "antd-mobile";
import { setCookie } from "cookies-next";
import copy from "@/utils/copy";

export default function SpringFestival() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const getBase = useCallback(
    (webviewBase) => {
      let searchParamsObj = null;
      let currentBaseCode = searchParams.get("base");
      if (currentBaseCode) {
        let currentBase = JSON.parse(currentBaseCode);
        searchParamsObj = { ...currentBase };
      }
      return searchParamsObj || webviewBase;
    },
    [searchParams]
  );

  const [data, setData] = useState([]);
  const [more, setMore] = useState(true);
  const [offset, setOffset] = useState(0);
  const [isFetching, setIsFetching] = useState(true);
  const [isLoading, setIsLoading] = useState(false);

  const getData = async () => {
    if (isLoading) return;
    setIsLoading(true);
    const webviewBase = webviewBaseRequest();
    let base = getBase(webviewBase);
    try {
      const response = await fetch(`/api/activity/zone_discount`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...base,
          offset: offset,
          limit: 10,
        }),
      });
      const _data = await response.json();
      if (_data.ret === -1) {
        Toast.show({
          content: _data.msg,
        });
        return;
      }
      setOffset(_data.data.offset);
      if (_data.data.more === 0) setMore(false);
      setData((prev) => [...prev, ..._data.data.list]);
    } catch (error) {
      console.error(error);
    } finally {
      setIsFetching(false);
      setIsLoading(false);
    }
  };

  useEffect(() => {
    setTimeout(() => {
      getData();
    }, 500);
  }, []);

  const InfiniteScrollContent = ({ hasMore }) => {
    return (
      <>
        {hasMore ? (
          <>
            <span className="text-[#FFFFFF80]">加载中...</span>
          </>
        ) : (
          <span className="text-[#FFFFFF80]">--- 我是有底线的 ---</span>
        )}
      </>
    );
  };

  const Card = ({ item }) => {
    return (
      <div
        className="basis-1/2 px-1 aspect-[140/200] cursor-pointer"
        onClick={() => {
          //如果是app内的webview打开
          const userAgent = navigator.userAgent;
          if (/FromWebview/i.test(userAgent)) {
            window.ReactNativeWebView.postMessage(
              JSON.stringify({
                type: "NAVIGATE",
                data: {
                  page: "SpaceIntroduce",
                  params: { mid: item?.mid },
                },
              })
            );
            return;
          }
          //如果是h5的iframe打开
          const webviewBase = webviewBaseRequest();
          let base = getBase(webviewBase);
          if (base?.b_token !== undefined) {
            window.top.location.href = `https://app.tiefen.fun/space/person_space_introduce/${item?.mid}`;
            return;
          }
          //如果直接从浏览器打开
          copy(
            `【${item?.name}】『ID:${item?.user_id}』,复制此条消息,打开铁粉空间APP,查看详情https://tiefen.fun/zone/${item?.user_id}`
          );
          setCookie("inviter", item?.user_id);
          router.push("/");
        }}
      >
        <div className="relative w-full">
          <img
            className="absolute top-0 left-0 w-full z-10"
            // src={
            //   process.env.NEXT_PUBLIC_CDN_URL +
            //   "/public/images/spring_festival_card_bg.png"
            // }
            src="/images/spring_festival_card_bg.png"
            alt=""
          />
          <img
            className="absolute top-0 left-0 w-full z-30"
            // src={
            //   process.env.NEXT_PUBLIC_CDN_URL +
            //   "/public/images/spring_festival_card_top.png"
            // }
            src="/images/spring_festival_card_top.png"
            alt=""
          />
          <div className="absolute top-0 left-0 w-full z-20 p-[4.2%]">
            <div className="relative">
              <img
                className="w-full aspect-square object-cover"
                src={item?.avatar?.images[0]?.urls[0]}
                alt=""
              />
              <div className="absolute left-0 bottom-0 z-10 flex items-center justify-center w-full h-8 bg-gradient-to-r from-[#FF4A8FEB] to-[#FF8E3EEB]">
                <p className="text-white text-sm">{item?.name}</p>
              </div>
            </div>
            <div className="flex flex-row justify-around items-center mt-1">
              <p className="text-xs text-[#68122280]">
                空间原价{" "}
                <span className="line-through">
                  ¥{item?.original_price / 100}
                </span>
              </p>
              <p className="text-2xl text-[#D71035] font-semibold">
                <span className="text-sm">¥</span>
                {item?.price / 100}
              </p>
            </div>
          </div>
        </div>
      </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>
    );
  }

  // 获取当前时间
  const currentDate = new Date();
  // 设置活动结束日期:2025年2月5日
  const targetDate = new Date("2025-02-05T00:00:00");

  // 判断当前时间是否在活动结束时间之后
  if (currentDate >= targetDate) {
    return (
      <section className="flex flex-col flex-1 bg-[#EE354F]">
        <img
          className="absolute top-0 left-0 z-0 w-full"
          src={
            process.env.NEXT_PUBLIC_CDN_URL +
            "/public/images/spring_festival_bg.png"
          }
          alt=""
        />
        <img
          className="absolute top-[72px] left-0 z-10 w-full"
          src={
            process.env.NEXT_PUBLIC_CDN_URL +
            "/public/images/spring_festival_title.png"
          }
          alt=""
        />
        <div className="w-full aspect-[308/252]"></div>
        <p className="text-center text-2xl font-bold text-white z-40">
          活动已结束
        </p>
      </section>
    );
  }

  return (
    <section className="flex flex-col flex-1 bg-[#EE354F]">
      <img
        className="absolute top-0 left-0 z-0 w-full"
        src={
          process.env.NEXT_PUBLIC_CDN_URL +
          "/public/images/spring_festival_bg.png"
        }
        alt=""
      />
      <img
        className="absolute top-[72px] left-0 z-10 w-full"
        src={
          process.env.NEXT_PUBLIC_CDN_URL +
          "/public/images/spring_festival_title.png"
        }
        alt=""
      />
      <div className="w-full aspect-[308/252]"></div>
      <div className="flex flex-1 flex-row flex-wrap px-3 z-10 w-full">
        {data?.map((item, index) => (
          <Card key={index} item={item} />
        ))}
      </div>
      <InfiniteScroll loadMore={() => getData()} hasMore={more}>
        <InfiniteScrollContent hasMore={more} />
      </InfiniteScroll>
    </section>
  );
}