import React, { useMemo, useState, useCallback, useRef, useEffect } from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';
import { useTheme } from 'tamagui';
import { useAppStore } from '@/stores';
import { GestureDetector } from 'react-native-gesture-handler';
import Animated, { useAnimatedStyle, interpolate } from 'react-native-reanimated';
import { wp } from '@/utils/ui/screenUtils';
import TabItem from '@/components/approve/TabItem';
import useTabPager from '@/hooks/useTabPager';
import useLazyMountTabs from '@/hooks/useLazyMountTabs';

const DEFAULT_TIMING = { duration: 240 };

export default function TabsPager({
  tabs = [],
  renderScene, // (i, tab, ctx) => ReactNode
  activeIndex,
  onIndexChange,
  initialIndex = 0,
  primaryColor: primaryColorProp,
  gap = wp(8),
  inset = wp(16),
  height = wp(34),
  timing = DEFAULT_TIMING,
  lazy = true,
  gestureEnabled = true,
  enableScroll = false,
  minTabWidth = wp(88),
  adaptiveWidth = false,
}) {
  const theme = useTheme();
  const primaryColorStore = useAppStore(s => s.primary);
  const primaryColor = primaryColorProp || primaryColorStore;

  const [containerWidth, setContainerWidth] = useState(0);
  const isControlled = typeof activeIndex === 'number' && typeof onIndexChange === 'function';
  const [innerIndex, setInnerIndex] = useState(initialIndex);
  const index = isControlled ? activeIndex : innerIndex;
  const setIndex = useCallback((i) => {
    if (isControlled) onIndexChange(i);
    else setInnerIndex(i);
  }, [isControlled, onIndexChange]);

  const { progress, panGesture, pagerAnimatedStyle } = useTabPager({
    activeIndex: index,
    setActiveIndex: setIndex,
    containerWidth,
    tabCount: tabs.length,
    timing,
  });

  const { shouldMount } = useLazyMountTabs(index, [0]);

  const scrollRef = useRef(null);
  const scrollXRef = useRef(0);
  const [tabWidths, setTabWidths] = useState([]);

  const slotW = useMemo(() => {
    const avg = containerWidth > 0 ? (containerWidth - inset * 2 - gap * (tabs.length - 1)) / (tabs.length || 1) : 0;
    return enableScroll ? Math.max(minTabWidth, avg) : avg;
  }, [containerWidth, inset, gap, tabs.length, enableScroll, minTabWidth]);

  const effectiveWidths = useMemo(() => {
    if (adaptiveWidth && enableScroll && containerWidth > 0) {
      if (tabWidths.length === tabs.length && tabWidths.every((v) => v > 0)) {
        return tabWidths;
      }
      return Array.from({ length: tabs.length }, () => Math.max(minTabWidth, slotW || 0));
    }
    return Array.from({ length: tabs.length }, () => slotW || 0);
  }, [adaptiveWidth, enableScroll, containerWidth, tabWidths, tabs.length, minTabWidth, slotW]);

  const positionsAbs = useMemo(() => {
    const arr = [];
    let acc = inset;
    for (let i = 0; i < effectiveWidths.length; i++) {
      arr.push(acc);
      acc += effectiveWidths[i] + gap;
    }
    return arr;
  }, [effectiveWidths, gap, inset]);

  const positionsRel = useMemo(() => positionsAbs.map((p) => p - inset), [positionsAbs, inset]);

  const contentWidth = useMemo(() => {
    if (!enableScroll) return containerWidth;
    if (containerWidth <= 0) return 0;
    const sumW = effectiveWidths.reduce((s, v) => s + v, 0);
    return inset * 2 + sumW + gap * (tabs.length - 1);
  }, [enableScroll, containerWidth, inset, tabs.length, gap, effectiveWidths]);

  const idxs = useMemo(() => effectiveWidths.map((_, i) => i), [effectiveWidths]);
  const indicatorAnimatedStyle = useAnimatedStyle(() => {
    if (!enableScroll || !adaptiveWidth || effectiveWidths.length !== tabs.length) {
      return { width: slotW, transform: [{ translateX: progress.value * (slotW + gap) }] };
    }
    const w = interpolate(progress.value, idxs, effectiveWidths);
    const tx = interpolate(progress.value, idxs, positionsRel);
    return { width: w, transform: [{ translateX: tx }] };
  });

  const handlePressTab = useCallback((i) => setIndex(i), [setIndex]);

  useEffect(() => {
    if (!enableScroll || containerWidth <= 0) return;
    const currentX = scrollXRef.current || 0;
    const leftEdge = currentX + inset;
    const rightEdge = currentX + containerWidth - inset;
    const tabLeft = positionsAbs[index] || (inset + index * (slotW + gap));
    const tabRight = tabLeft + (effectiveWidths[index] || slotW);
    let targetX = currentX;
    if (tabLeft < leftEdge) {
      targetX = tabLeft - inset;
    } else if (tabRight > rightEdge) {
      targetX = tabRight - (containerWidth - inset);
    }
    const maxScroll = Math.max(0, (contentWidth || 0) - containerWidth);
    targetX = Math.max(0, Math.min(targetX, maxScroll));
    if (scrollRef.current && Math.abs(targetX - currentX) > 1) {
      scrollRef.current.scrollTo({ x: targetX, animated: true });
      scrollXRef.current = targetX;
    }
  }, [index, enableScroll, containerWidth, inset, slotW, gap, contentWidth, positionsAbs, effectiveWidths]);

  const SIDE_PADDING = wp(20);
  const handleLabelLayout = useCallback((i, w) => {
    if (!adaptiveWidth || !enableScroll) return;
    const rawW = typeof w === 'number' ? w : 0;
    const nextW = Math.max(minTabWidth, rawW + SIDE_PADDING);
    setTabWidths((prev) => {
      const base = prev.length === tabs.length ? prev.slice() : Array.from({ length: tabs.length }, () => Math.max(minTabWidth, slotW || 0));
      if (Math.abs((base[i] || 0) - nextW) <= 0.5) return prev;
      base[i] = nextW;
      return base;
    });
  }, [adaptiveWidth, enableScroll, minTabWidth, tabs.length, slotW, SIDE_PADDING]);

  const pagerContent = (
    <View style={{ overflow: 'hidden', marginTop: wp(12), flex: 1 }}>
      <Animated.View
        style={[
          { width: containerWidth * tabs.length, flexDirection: 'row', height: '100%' },
          pagerAnimatedStyle,
        ]}
      >
        {tabs.map((t, i) => (
          <View key={t.key || String(i)} style={{ width: containerWidth, flex: 1 }}>
            {!lazy || shouldMount(i) ? (
              renderScene?.(i, t, { containerWidth, isActive: index === i })
            ) : null}
          </View>
        ))}
      </Animated.View>
    </View>
  );

  return (
    <View style={{ flex: 1 }}>
      <View
        onLayout={(e) => setContainerWidth(e.nativeEvent.layout.width)}
        style={[styles.segmentContainer, { height }]}
      >
        {enableScroll ? (
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            ref={scrollRef}
            onScroll={(e) => { scrollXRef.current = e.nativeEvent.contentOffset.x; }}
            scrollEventThrottle={16}
            style={{overflow: 'visible'}}
          >
            <View style={{ width: contentWidth, height }}>
              {containerWidth > 0 && tabs.map((_, i) => (
                <View
                  key={`rail-${i}`}
                  style={[
                    styles.segmentRail,
                    { left: positionsAbs[i] || (inset + i * (slotW + gap)), width: effectiveWidths[i] || slotW, height },
                  ]}
                />
              ))}

              {containerWidth > 0 ? (
                <Animated.View
                  pointerEvents="none"
                  style={[styles.segmentIndicator, { left: inset, height, backgroundColor: primaryColor }, indicatorAnimatedStyle]}
                />
              ) : null}

              <View style={{ flexDirection: 'row', paddingHorizontal: inset, height: '100%' }}>
                {tabs.map((t, i) => (
                  <TabItem
                    key={t.key || String(i)}
                    t={{ label: t.title || t.label, badge: t.badge }}
                    i={i}
                    activeSV={progress}
                    onPress={handlePressTab}
                    containerWidth={containerWidth}
                    tabCount={tabs.length}
                    gap={gap}
                    color={primaryColor}
                    slotW={(adaptiveWidth && enableScroll ? (effectiveWidths[i] || slotW) : slotW)}
                    step={slotW + gap}
                    fixedWidthMode
                    adaptiveWidth={adaptiveWidth && enableScroll}
                    positionsRel={positionsRel}
                    widths={effectiveWidths}
                    onLabelLayout={(w) => handleLabelLayout(i, w)}
                  />
                ))}
              </View>
            </View>
          </ScrollView>
        ) : (
          <>
            {containerWidth > 0 && tabs.map((_, i) => (
              <View
                key={`rail-${i}`}
                style={[
                  styles.segmentRail,
                  { left: inset + i * (slotW + gap), width: slotW, height },
                ]}
              />
            ))}

            {containerWidth > 0 ? (
              <Animated.View
                pointerEvents="none"
                style={[styles.segmentIndicator, { left: inset, height, backgroundColor: primaryColor }, indicatorAnimatedStyle]}
              />
            ) : null}

            <View style={{ flexDirection: 'row', paddingHorizontal: inset, width: '100%', height: '100%' }}>
              {tabs.map((t, i) => (
                <TabItem
                  key={t.key || String(i)}
                  t={{ label: t.title || t.label, badge: t.badge }}
                  i={i}
                  activeSV={progress}
                  onPress={handlePressTab}
                  containerWidth={containerWidth}
                  tabCount={tabs.length}
                  gap={gap}
                  color={primaryColor}
                  slotW={slotW}
                  step={slotW + gap}
                  onLabelLayout={undefined}
                />
              ))}
            </View>
          </>
        )}
      </View>

      {gestureEnabled ? (
        <GestureDetector gesture={panGesture}>{pagerContent}</GestureDetector>
      ) : (
        pagerContent
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  segmentContainer: {
    position: 'relative',
    backgroundColor: 'transparent',
    borderRadius: wp(0),
    padding: wp(0),
    flexDirection: 'row',
    alignItems: 'center',
    // 尝试为顶部栏强制独立图层，降低与重内容的合成开销
    renderToHardwareTextureAndroid: true,
    shouldRasterizeIOS: true,
  },
  segmentRail: {
    position: 'absolute',
    top: wp(0),
    left: wp(0),
    backgroundColor: '#fff',
    borderRadius: wp(6),
    zIndex: 0,
    // 轻微阴影，避免白色背景下不可见
    shadowColor: '#000',
    shadowOpacity: 0.06,
    shadowRadius: 4,
    shadowOffset: { width: 0, height: 2 },
    elevation: 2,
  },
  segmentIndicator: {
    position: 'absolute',
    top: wp(0),
    left: wp(0),
    backgroundColor: '#6A4CFF',
    borderRadius: wp(6),
    zIndex: 1,
    // 指示器也独立到硬件层，减少重绘卡顿
    renderToHardwareTextureAndroid: true,
    shouldRasterizeIOS: true,
  },
});
