import React from 'react';
import { Pressable, StyleSheet } from 'react-native';
import { View } from 'tamagui';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
  interpolate,
  Extrapolation,
  interpolateColor,
  Easing,
  LinearTransition,
  FadeIn,
  FadeOut,
} from 'react-native-reanimated';
import { wp } from '@/utils/ui/screenUtils';

const styles = StyleSheet.create({
  containerBase: {
    width: wp(307),
    borderRadius: wp(4),
    borderWidth: wp(1),
    // 保持收起时的最小高度，配合 Layout 动画无需显式测量
    minHeight: wp(57),
  },
  pressableFill: { flex: 1 },
  collapsedLayer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    height: wp(57),
    justifyContent: 'center',
    //为了卡片收缩状态下的视觉垂直居中
  paddingBottom:wp(2),
    paddingHorizontal: wp(15),
    backfaceVisibility: 'hidden',
  },
  expandedPadding: {
    paddingHorizontal: wp(16),
    paddingBottom: wp(17),
    backfaceVisibility: 'hidden',
  },
});

/**
 * 动画手风琴组件
 * @param {boolean} isExpanded - 是否展开
 * @param {function} onToggle - 切换展开状态的回调
 * @param {React.ReactNode} collapsedContent - 收缩状态显示的内容
 * @param {React.ReactNode} expandedContent - 展开状态显示的内容
 * @param {object} theme - 主题对象
 * @param {object} containerStyle - 容器样式
 * @param {object} collapsedStyle - 收缩状态样式
 * @param {object} expandedStyle - 展开状态样式
 */
const AnimatedAccordionItem = ({ 
  isExpanded, 
  onToggle, 
  collapsedContent, 
  expandedContent, 
  containerStyle = {},
  collapsedStyle = {},
  expandedStyle = {}
}) => {
  const animatedHeight = useSharedValue(0);
  // 避免在 worklet 内调用非 worklet 函数
  const { collapsedBg, collapsedBorder, expandedBg, expandedBorder } = React.useMemo(() => {
    const c = StyleSheet.flatten(collapsedStyle) || {};
    const e = StyleSheet.flatten(expandedStyle) || {};
    return {
      collapsedBg: c.backgroundColor || '#EEE9F8',
      collapsedBorder: c.borderColor || '#FFF',
      expandedBg: e.backgroundColor || '#fff',
      expandedBorder: e.borderColor || '#E0E0E4',
    };
  }, [collapsedStyle, expandedStyle]);

  React.useEffect(() => {
    animatedHeight.value = withTiming(isExpanded ? 1 : 0, { duration: 300, easing: Easing.out(Easing.cubic) });
  }, [isExpanded]);

  const animatedStyle = useAnimatedStyle(() => ({
    // Layout 动画负责高度变化，这里仅控制溢出与必要样式
    overflow: 'hidden',
  }));

  // 透明度改由 entering/exiting 控制，避免与布局动画冲突
  
  // 颜色动画样式（仅使用已计算好的字符串常量）
  const colorAnimatedStyle = useAnimatedStyle(() => {
    const backgroundColor = interpolateColor(
      animatedHeight.value,
      [0, 1],
      [collapsedBg, expandedBg]
    );

    const borderColor = interpolateColor(
      animatedHeight.value,
      [0, 1],
      [collapsedBorder, expandedBorder]
    );

    return {
      backgroundColor,
      borderColor,
    };
  });

  return (
    <Animated.View 
      style={[
        animatedStyle,
        colorAnimatedStyle,
        styles.containerBase,
        containerStyle
      ]}
      // 使用 UI 线程 Layout 动画，避免显式高度插值与重复测量
      layout={LinearTransition.duration(240).easing(Easing.out(Easing.cubic))}
    >
      <Pressable onPress={onToggle} style={styles.pressableFill}>
        {/* 收缩状态内容：仅在未展开时渲染，淡入淡出避免与布局动画冲突 */}
        {!isExpanded ? (
          <Animated.View 
            style={[
              styles.collapsedLayer,
            ]}
            entering={FadeIn.duration(160)}
            exiting={FadeOut.duration(140)}
          >
            {collapsedContent}
          </Animated.View>
        ) : null}
        
        {/* 展开状态内容 - 实际显示（进入/退出淡入淡出） */}
        {isExpanded ? (
          <Animated.View 
            style={[
              styles.expandedPadding,
            ]}
            entering={FadeIn.duration(180)}
            exiting={FadeOut.duration(140)}
            layout={LinearTransition.duration(240).easing(Easing.out(Easing.cubic))}
          >
            {expandedContent}
          </Animated.View>
        ) : null}
      </Pressable>
    </Animated.View>
  );
};

export default React.memo(AnimatedAccordionItem);