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; // 上下滚动背景渐变
}

const Index: React.FC<Props> = ({
  leftColumn,
  children,
  center = true,
  onNavBack,
  blur = false,
  navDelta = 1,
  backText,
  scrollFadeIn = false,
}) => {
  const statusBarHeight = useAppStore.getState().statusBarHeight;
  //
  const [opacity, setOpacity] = useState(scrollFadeIn ? 1 : 0);
  usePageScroll((e) => {
    if (!scrollFadeIn) {
      return;
    }
    const opacity = Math.max(0, e.scrollTop / 50);
    setOpacity(opacity);
    // 如果 setShow 此处打开，滚动页内如果有图片会导致转自跳动 bug
    // setShow(opacity !== 0)
  });

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

    if (onNavBack) {
      console.log("nav");
      await onNavBack();
      Taro.navigateBack({
        delta: navDelta,
        complete: () => {
          
        },
      });
    } else {
      Taro.navigateBack({
        complete: () => {
          
        },
      });
    }
  };

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

    // 文本返回按钮
    return (
      <View className={`${style.navBarBackButtonNormal}`}>
        <IconArrowLeft />
        {/* <View className={`${style.iconArrowLeftPure}`}></View> */}
        <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} ${blur ? style.backdropFilter : ''}`}
        id="leaf-nav-bar"
        style={{
          paddingTop: statusBarHeight,
        }}
      >
        <View className={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;
