import type { NativeStackNavigationOptions } from "@react-navigation/native-stack";
import { useNavigation } from "expo-router";
import { useLayoutEffect, useMemo } from "react";
import { Image } from "tamagui";
import CustomText from '@/components/common/CustomText.jsx';
import { TouchableOpacity } from "react-native";
import { Header } from "@react-navigation/elements";
import { wp } from "@/utils/ui/screenUtils";
import { useSafeAreaInsets } from "react-native-safe-area-context";

interface CustomHeaderProps extends NativeStackNavigationOptions {
  useCustomStyle?: boolean; // 是否使用自定义样式，默认为true
  leftContent?: React.ReactNode; // 自定义左侧内容
  centerContent?: React.ReactNode; // 自定义中间内容
  rightContent?: React.ReactNode; // 自定义右侧内容
  onBackPress?: () => void; // 点击默认返回按钮的回调
}

const FIXED_HEADER_HEIGHT = wp(50); // 统一固定的标题栏高度（不含状态栏安全区）

// 自定义Header组件，只自定义样式，依旧使用Stack的特性
export const CustomHeader = ({ useCustomStyle = true, ...props }: CustomHeaderProps) => {
  // 使用 useNavigation 设置自定义样式的Stack导航
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();
  const customOptions = useMemo(() => {
    if (!useCustomStyle) return {};
    return {
      headerLeft: () => props.leftContent ?? defaultBackBtn(navigation, props.onBackPress),
      headerTitle: () => props.centerContent ?? defaultTitle(props),
      headerRight: () => props.rightContent,
      headerTitleAlign: props.headerTitleAlign ?? "center", // 标题对齐方式居中
      headerBackButtonDisplayMode:
        props.headerBackButtonDisplayMode ?? "minimal", //IOS上返回按钮使用的标题字符串
      // 通过自定义 Header 固定标题栏本体高度，并叠加状态栏安全区
      header: ({ options }) => (
        <Header
          {...(options as any)}
          title={options.title ?? ""}
          headerStatusBarHeight={insets.top}
          headerStyle={[options.headerStyle, { height: insets.top + FIXED_HEADER_HEIGHT }]}
        />
      ),
    } as NativeStackNavigationOptions;
  }, [props, navigation, insets.top]);

  useLayoutEffect(() => {
    navigation.setOptions({
      ...props, // 透传所有原生参数
      ...customOptions, // 覆盖自定义header
    });
  }, [navigation, props, customOptions]);

  // 不返回任何UI，因为Stack会自动处理
  return null;
};

// 默认返回按钮
const defaultBackBtn = (navigation: any, onBackPress?: () => void) => {
  return (
    <TouchableOpacity
      style={{ paddingLeft: wp(16), paddingRight: wp(32), paddingVertical: wp(10) }}
      hitSlop={{ top: wp(8), bottom: wp(8), left: wp(12), right: wp(12) }}
      onPress={() => (onBackPress ? onBackPress() : navigation.goBack())}
    >
      <Image style={{ width: wp(9), height: wp(17) }} source={require("@/assets/images/icon/back-btn-black.png")} />
    </TouchableOpacity>
  );
};

// 默认标题
const defaultTitle = (props: CustomHeaderProps) => {
  return (
    <CustomText style={{ fontSize: wp(17), fontFamily: "Bold", lineHeight: wp(24) }}>
      {props.title}
    </CustomText>
  );
};
export default CustomHeader;