import { memo, useMemo, useRef, useState } from "react";
import {
  Image,
  View,
  Text,
  Video,
  Swiper,
  SwiperItem,
} from "@tarojs/components";
import classNames from "classnames";
import Taro, {
  FC,
  nextTick,
  pxTransform,
  useDidHide,
  useDidShow,
} from "@tarojs/taro";
import { Menu } from "./components/Menu";
import BtmBgImg from "../../images/img_city-min.png";
import BgImg from "../../images/img_map@2x-min.jpg";
import CloudImg from "../../images/img_cloud-min.png";
import LeftIcon from "../../images/icon_blue_left@2x-min.png";
import RightIcon from "../../images/icon_blue_right@2x-min.png";
import ButtonImg from "../../images/btn_start@2x-min.png";
import { Swiper as SightSwiper, SwiperMethods } from "./components/Swiper";
import { SearchLayout } from "./components/SearchLayout";
import { SightDetailLayout } from "./components/SightDetailLayout";
import { SIGHT_LIST, SORT_MAP_ID } from "./constants";
import { checkLoginApi, getSignListApi } from "../../api";
import { VisitCard } from "./components/VisitCard";
import { getSceneUrl, NICKNAME_key, TOKEN_KEY } from "../../utils";
import baseStore from "../../store/base";
import "./index.scss";

const PointIcon = memo(() => {
  return (
    <>
      {SIGHT_LIST.map((item) => (
        <View
          key={item.id}
          className={classNames("home__point-icon", [
            Math.round(Math.random()) ? "" : "red",
          ])}
          style={{
            top: pxTransform(item.pos.y),
            left: pxTransform(item.pos.x),
          }}
        />
      ))}
    </>
  );
});

const bgScale = Math.round(1558 / 778);
const system = Taro.getSystemInfoSync();
const imgHeight = bgScale * system.windowWidth;
const offsetHeight =
  imgHeight > system.screenHeight ? imgHeight - system.screenHeight : 0;

const HomePage: FC = () => {
  const [curSwiper, setCurSwiper] = useState(0);
  const [loaded, setLoaded] = useState(false);
  const [visitVisible, setVisitVisible] = useState(false);
  const [hideLoading, setHideLoading] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const [showSearch, setShowSearch] = useState(false);
  const [showSight, setShowSight] = useState(false);
  const swiperRef = useRef<SwiperMethods>(null);
  const [curSwiperItem, setCurSwiperItem] = useState(10);
  const [item, setItem] = useState(
    SIGHT_LIST.find((i) => i.id === SORT_MAP_ID[curSwiperItem])
  );

  const realItem = useMemo(
    () => SIGHT_LIST.find((i) => i.id === SORT_MAP_ID[curSwiperItem]),
    [curSwiperItem]
  );

  const openSearch = () => {
    setShowMenu(false);
    setShowSearch(true);
  };

  const handleDetail = async () => {
    swiperRef.current?.setIsRunning(false);
    const target = SIGHT_LIST.find((i) => i.id === SORT_MAP_ID[curSwiperItem]);
    const data = await getSignListApi({
      searchKey: target?.title,
      type: "scene",
    });
    setItem(data[0] || target);
    setShowSight(true);
  };

  const closeDetail = () => {
    setShowSight(false);
    curSwiper === 0 && swiperRef.current?.setIsRunning(true);
  };

  const closeMenu = () => {
    setShowMenu(false);
    curSwiper === 0 && swiperRef.current?.setIsRunning(true);
  };

  const handleLoaded = () => {
    nextTick(() => {
      setLoaded(true);
      swiperRef.current?.setIsRunning(true);

      setTimeout(() => {
        setHideLoading(true);
      }, 1000);
    });
  };

  const checkLogin = async () => {
    try {
      Taro.showLoading({
        title: "登录中...",
      });
      const data = await checkLoginApi();

      if (data) {
        baseStore.isLogin = true;
        Taro.navigateTo({
          url:
            "/subModule/pages/iframe/index?url=" +
            encodeURIComponent(getSceneUrl()),
        });
      } else {
        Taro.removeStorageSync(TOKEN_KEY);
        Taro.removeStorageSync(NICKNAME_key);
      }
    } finally {
      Taro.hideLoading();
    }
  };

  useDidShow(() => {
    loaded && swiperRef.current?.setIsRunning(true);
  });
  useDidHide(() => {
    swiperRef.current?.setIsRunning(false);
  });

  return (
    <>
      <View
        className="home__menu-btn"
        onClick={() => {
          setShowMenu(true);
          swiperRef.current?.setIsRunning(false);
        }}
      />

      <Menu show={showMenu} onClose={closeMenu} openSearch={openSearch} />

      <Swiper
        vertical
        current={curSwiper}
        style={{ height: "100vh" }}
        onChange={(v) => {
          setCurSwiper(v.detail.current);
          swiperRef.current?.setIsRunning(v.detail.current === 0);
        }}
      >
        <SwiperItem className="home-container">
          <View className="home">
            <View
              className="home-main"
              style={{
                top: `${-offsetHeight}px`,
              }}
            >
              {realItem && (
                <View
                  className="home__point"
                  style={{
                    top: pxTransform(realItem.pos.y),
                    left: pxTransform(realItem.pos.x),
                  }}
                />
              )}

              <PointIcon />

              <SightSwiper
                ref={swiperRef}
                curSwiperItem={curSwiperItem}
                setCurSwiperItem={setCurSwiperItem}
              />

              <View className="home-toggle">
                <Image
                  className="home-toggle__icon"
                  src={LeftIcon}
                  onClick={() => swiperRef.current?.toPrev()}
                />

                <View className="home-toggle-inner">
                  <View className="home-toggle-label">
                    <Text className="home-toggle-label__title limit-line">
                      {realItem?.title}
                    </Text>
                    <Text>{realItem?.address}</Text>
                  </View>

                  <View
                    className="home-toggle__detail"
                    onClick={handleDetail}
                  />
                </View>

                <Image
                  className="home-toggle__icon"
                  src={RightIcon}
                  onClick={() => swiperRef.current?.toNext()}
                />
              </View>
            </View>

            <View className="home-main__btn" onClick={() => setCurSwiper(1)}>
              <View className="flashing">
                <View>探索锡善云城</View>
                <View className="reflect">探索锡善云城</View>
              </View>
            </View>

            <Image
              className="home__bg"
              src={BgImg}
              mode="widthFix"
              style={{
                top: `${-offsetHeight}px`,
              }}
            />
            <Image className="home__btm-bg" src={BtmBgImg} mode="widthFix" />
            <Image
              className="home__cloud cloud1"
              src={CloudImg}
              mode="heightFix"
            />
            <Image
              className="home__cloud cloud2"
              src={CloudImg}
              mode="heightFix"
            />
          </View>
        </SwiperItem>

        <SwiperItem className="home2">
          <Image
            className="home2__btn"
            src={ButtonImg}
            mode="widthFix"
            onClick={() => {
              const token = Taro.getStorageSync(TOKEN_KEY);

              if (token) {
                checkLogin();
              } else {
                setVisitVisible(true);
              }
            }}
          />
        </SwiperItem>
      </Swiper>

      {!loaded && (
        <Video
          className={classNames("home-loading", {
            hide: loaded,
            close: hideLoading,
          })}
          src="https://houseoss.4dkankan.com/project/wx-csbwg-public/videos/loading.mp4"
          autoplay
          muted
          controls={false}
          objectFit="cover"
          onEnded={handleLoaded}
          onError={handleLoaded}
        />
      )}

      <SearchLayout
        isOpened={showSearch}
        onClose={() => setShowSearch(false)}
        openDetail={(item) => {
          swiperRef.current?.setIsRunning(false);
          setItem(item);
          setShowSight(true);
        }}
      />

      {item && (
        <SightDetailLayout
          item={item}
          isOpened={showSight}
          onClose={closeDetail}
        />
      )}

      <VisitCard
        isOpened={visitVisible}
        onClose={() => setVisitVisible(false)}
      />
    </>
  );
};

export default HomePage;
