import React, { useEffect, useState, useRef, useCallback } from "react";
import { Toast, Swiper, Image } from "antd-mobile";
import LoadingMask from "@/components/LoadingMask";
import { useRouter } from "next/navigation";
import requireAPI from "@/utils/requireAPI";
import OwnImage from "@/components/OwnImage";
import { goToPage } from "@/utils/tools";
export default function Banner() {
  const [bannerList, setBannerList] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();
  const ref = useRef(null);
  useEffect(() => {
    const getBannerList = async () => {
      setIsLoading(true);
      try {
        const _data = await requireAPI(
          "POST",
          "/api/activity_banner/list",
          null,
          true
        );
        if (_data.ret === -1) {
          Toast.show({
            icon: "fail",
            content: _data.msg,
            position: "top",
          });
          return;
        }
        setBannerList(_data.data.list);
      } catch (error) {
        console.error(error);
      } finally {
        setIsLoading(false);
      }
    };
    getBannerList();
  }, []);
  const items = useCallback(
    (item, index) => (
      <Swiper.Item key={index}>
        <div
          className="w-full h-[200px]"
          onClick={() => {
            const links = item?.hyperlinks;
            if (links.length > 1) {
              router.push(
                links.filter((it) => it.inward_action_type === "h5")[0]?.url
              );
            } else {
              router.push(links[0]?.url);
            }
          }}
        >
          <OwnImage
            className={"w-full h-full"}
            outClassName={"w-full h-full"}
            src={item.image.images[0].urls[0]}
            fit="cover"
            position="center"
          />
        </div>
      </Swiper.Item>
    ),
    []
  );
  return (
    <div className="flex-1 mt-6">
      <Swiper
        allowTouchMove
        ref={ref}
        loop
        autoplay
        style={{ "--border-radius": "8px" }}
      >
        {bannerList.map((item, index) => items(item, index))}
      </Swiper>
    </div>
  );
}
