import React, { useCallback } from 'react';
import { Pressable, StyleSheet } from 'react-native';
import { View } from 'tamagui';
import CustomText from '@/components/common/CustomText.jsx';
import Animated, { useAnimatedStyle, interpolate } from 'react-native-reanimated';
import { wp, hp } from '@/utils/ui/screenUtils';
import { useAppStore } from '@/stores';

const TabItem = ({ t, i, activeSV, onPress, containerWidth, tabCount, gap, color, slotW, step, fixedWidthMode = false, adaptiveWidth = false, positionsRel, widths, onLabelLayout }) => {
  const primaryColorStore = useAppStore(s => s.primary);
  const primaryColor = color || primaryColorStore;

  const maskStyle = useAnimatedStyle(() => {
    if (!adaptiveWidth || !Array.isArray(widths) || !Array.isArray(positionsRel)) {
      const slot = slotW ?? (containerWidth > 0 ? (containerWidth - gap * (tabCount - 1)) / tabCount : 0);
      const s = step ?? (slot + gap);
      const tabLeft = i * s;
      const indLeft = activeSV.value * s;
      const leftInTab = Math.max(0, indLeft - tabLeft);
      const overlap = Math.max(0, Math.min(tabLeft + slot, indLeft + slot) - Math.max(tabLeft, indLeft));
      return { left: leftInTab, width: overlap };
    }
    const idxs = widths.map((_, k) => k);
    const slot = widths[i] || 0;
    const tabLeftRel = positionsRel[i] || 0;
    const indLeftRel = interpolate(activeSV.value, idxs, positionsRel);
    const indWidth = interpolate(activeSV.value, idxs, widths);
    const leftInTab = Math.max(0, indLeftRel - tabLeftRel);
    const overlap = Math.max(0, Math.min(tabLeftRel + slot, indLeftRel + indWidth) - Math.max(tabLeftRel, indLeftRel));
    return { left: leftInTab, width: overlap };
  });

  const innerStyle = useAnimatedStyle(() => {
    if (!adaptiveWidth || !Array.isArray(widths) || !Array.isArray(positionsRel)) {
      const slot = slotW ?? (containerWidth > 0 ? (containerWidth - gap * (tabCount - 1)) / tabCount : 0);
      const s = step ?? (slot + gap);
      const tabLeft = i * s;
      const indLeft = activeSV.value * s;
      const leftInTab = Math.max(0, indLeft - tabLeft);
      return { left: -leftInTab, width: slot };
    }
    const idxs = widths.map((_, k) => k);
    const slot = widths[i] || 0;
    const tabLeftRel = positionsRel[i] || 0;
    const indLeftRel = interpolate(activeSV.value, idxs, positionsRel);
    const leftInTab = Math.max(0, indLeftRel - tabLeftRel);
    return { left: -leftInTab, width: slot };
  });

  const handlePress = useCallback(() => onPress(i), [onPress, i]);

  return (
    <Pressable
      style={[
        styles.segmentItem,
        fixedWidthMode ? { width: slotW } : { flex: 1 },
        i !== tabCount - 1 && { marginRight: gap },
      ]}
      onPress={handlePress}
    >
      <Animated.View style={[styles.segmentPill, fixedWidthMode && { width: '100%' }]}> 
        <CustomText style={[styles.segmentText, { color: primaryColor, fontSize: wp(14) }]} numberOfLines={1} ellipsizeMode="tail" onLayout={(e) => onLabelLayout && onLabelLayout(e?.nativeEvent?.layout?.width || 0)}>{t.label}</CustomText>
        <Animated.View pointerEvents="none" style={[styles.maskClip, maskStyle]}> 
          <Animated.View style={[styles.maskInner, innerStyle]}> 
            <CustomText style={[styles.segmentText, { color: '#FFFFFF', fontSize: wp(14) }]} numberOfLines={1} ellipsizeMode="tail">{t.label}</CustomText>
          </Animated.View>
        </Animated.View>
        {t.badge ? (
          <View position="absolute" top={-wp(8)} right={wp(-7)} backgroundColor="#F04438" paddingHorizontal={wp(6)} height={wp(18)} minWidth={wp(18)} alignItems="center" justifyContent="center" borderRadius={wp(9)} zIndex={4}>
            <CustomText style={{ color: '#fff', fontSize: wp(11) }}>{t.badge}</CustomText>
          </View>
        ) : null}
      </Animated.View>
    </Pressable>
  );
};

const styles = StyleSheet.create({
  segmentItem: {
    height: '100%',
    position: 'relative',
    zIndex: 2,
  },
  segmentPill: {
    height: '100%',
    borderRadius: wp(6),
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
    zIndex: 2,
    // 将按钮 pill 提升为独立图层，减少与复杂内容的交互重绘
    renderToHardwareTextureAndroid: true,
    shouldRasterizeIOS: true,
  },
  segmentText: {
    fontFamily: 'Bold',
  },
  maskClip: {
    position: 'absolute',
    top: wp(0),
    height: '100%',
    overflow: 'hidden',
    zIndex: 3,
    borderRadius: wp(6),
    // 蒙版也尽可能独立，降低反复布局造成的卡顿感知
    renderToHardwareTextureAndroid: true,
    shouldRasterizeIOS: true,
  },
  maskInner: {
    position: 'absolute',
    top: wp(0),
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default React.memo(TabItem, (prev, next) => {
  return (
    prev.i === next.i &&
    prev.t?.label === next.t?.label &&
    prev.t?.badge === next.t?.badge &&
    prev.containerWidth === next.containerWidth &&
    prev.tabCount === next.tabCount &&
    prev.gap === next.gap &&
    prev.color === next.color &&
    prev.slotW === next.slotW &&
    prev.step === next.step &&
    prev.onPress === next.onPress &&
    prev.activeSV === next.activeSV &&
    prev.fixedWidthMode === next.fixedWidthMode
  );
});
