import { useAppStore } from "@/store/appStore";
import { Text, View } from "@tarojs/components";
import Taro, { useUnload, usePageScroll } from "@tarojs/taro";
import React, { useState } from "react";
import IconArrowLeft from "@/components/icon/icon-arrow-left";
import style from "./index.module.less";

interface Props {
  children?: React.ReactChild;
  center?: boolean;
  leftColumn?: () => JSX.Element;
  backText?: string;
  blur?: boolean
  onNavBack?: () => Promise<boolean | void> | void;
  backButtonRound?: boolean;
  navDelta?: number;
  scrollFadeIn?: boolean; // 上下滚动背景渐变
  scrollFadeInDelta?: number // 开始背景渐变效果的阈值
}

const Index: React.FC<Props> = ({
  leftColumn,
  children,
  center = true,
  onNavBack,
  blur = false,
  navDelta = 1,
  backText,
  scrollFadeIn = false,
  scrollFadeInDelta = 0,
}) => {
  const statusBarHeight = useAppStore.getState().statusBarHeight;
  const ratio = useAppStore.getState().ratio;
  //
  const [opacity, setOpacity] = useState(scrollFadeIn ? 0 : 1);
  usePageScroll((e) => {
    if (!scrollFadeIn) {
      return;
    }

    // 如果 scrollTop 小于可变化阈值，则不产生变化
    if(e.scrollTop < scrollFadeInDelta){
      setOpacity(0)
      return;
    }
    // 变化时 e.scrollTop  / (阈值 + 88 )
    const opacity = Math.max(0, e.scrollTop / (scrollFadeInDelta + 88));
    setOpacity(opacity);
    // 如果 setShow 此处打开，滚动页内如果有图片会导致转自跳动 bug
    // setShow(opacity !== 0)
  });

  const handleNav = async () => {
    // 无法将 导航栏隐藏，只能用 opacity 为 0
    // 否则滚动页内如果有图片会导致转自跳动 bug

    if (onNavBack) {
      console.log("nav");
      const result = await onNavBack();
      if(result !== false){
        Taro.navigateBack({
          delta: navDelta,
        });
      }

    } else {
      Taro.navigateBack();
    }
  };

  // todo: 改成传参决定是否显示：箭头|文本|箭头与文本
  const renderBackButton = () => {
    // 如果显示背景色，则返回按钮不需要圆角及背景

    // 文本返回按钮
    return (
      <View className={`${style.navBarBackButtonNormal}`}>
        <IconArrowLeft />
        <Text className={style.backText}>{backText}</Text>
      </View>
    );
  };

  const renderLeftColumn = () => {
    if (leftColumn) {
      return <View className={style.leftColumn}>{leftColumn()}</View>;
    } else {
      return (
        <View className={style.leftColumn} onClick={handleNav}>
          {renderBackButton()}
        </View>
      );
    }
  };

  const renderNavBar = () => {
    return (
      <View
        className={`${style.navBarContainer}`}
        id="leaf-nav-bar"
        style={{
          paddingTop: `${statusBarHeight * ratio}rpx`,
        }}
      >
        {/* 背景毛玻璃与 渐变背景互斥 */}
        <View className={`${style.navBarBgContainer} ${blur ? style.backdropFilter : style.navBarBg}`} style={{opacity: opacity}}></View>
        <View className={`${style.navBar}`}>
          {renderLeftColumn()}
          <View
            className={`flex flex-1 ${center ? "justify-center" : ""} ${
              style.title
            } truncate`}
          >
            {children}
          </View>
          <View className={style.rightColumn}></View>
        </View>
      </View>
    );
  };

  return <>{renderNavBar()}</>;
};

export default Index;
