import { useEffect, useMemo } from 'react';
import { useSharedValue, useAnimatedStyle, withTiming, runOnJS } from 'react-native-reanimated';
import { Gesture } from 'react-native-gesture-handler';

/**
 * 管理分页进度、滑动手势与翻页动画
 * @param {object} params
 * @param {number} params.activeIndex 当前激活索引
 * @param {(i:number)=>void} params.setActiveIndex 设置激活索引
 * @param {number} params.containerWidth 容器宽度
 * @param {number} params.tabCount Tab 总数
 * @param {{duration:number,easing:any}} params.timing 动画配置
 */
export default function useTabPager({ activeIndex, setActiveIndex, containerWidth, tabCount, timing }) {
  const progress = useSharedValue(activeIndex);
  const indexSV = useSharedValue(activeIndex);
  const startIndexSV = useSharedValue(activeIndex);
  const containerWidthSV = useSharedValue(containerWidth || 0);

  // 容器宽度同步到 UI 线程
  useEffect(() => {
    containerWidthSV.value = containerWidth || 0;
  }, [containerWidth]);

  // 索引变化时驱动动画
  useEffect(() => {
    progress.value = withTiming(activeIndex, timing);
    indexSV.value = activeIndex;
  }, [activeIndex]);

  const pagerAnimatedStyle = useAnimatedStyle(() => ({
    // 使用 UI 线程上的宽度值，避免依赖 JS 闭包变量引发同步抖动
    transform: [{ translateX: -progress.value * containerWidthSV.value }],
  }));

  const panGesture = useMemo(() => {
    const SWIPE_TRIGGER_RATIO = 0.2;
    const VELOCITY_TRIGGER = 600; // px/s
    return Gesture.Pan()
      .activeOffsetX([-8, 8])
      .failOffsetY([-14, 14])
      .onBegin(() => {
        startIndexSV.value = indexSV.value;
      })
      .onUpdate((e) => {
        const w = containerWidthSV.value;
        if (w <= 0) return;
        const max = tabCount - 1;
        const raw = startIndexSV.value - e.translationX / w;
        const clamped = Math.max(0, Math.min(max, raw));
        progress.value = clamped;
      })
      .onEnd((e) => {
        const max = tabCount - 1;
        const delta = progress.value - startIndexSV.value;
        let target = startIndexSV.value;
        if (delta >= SWIPE_TRIGGER_RATIO || e.velocityX <= -VELOCITY_TRIGGER) {
          target = Math.min(max, Math.round(startIndexSV.value + 1));
        } else if (delta <= -SWIPE_TRIGGER_RATIO || e.velocityX >= VELOCITY_TRIGGER) {
          target = Math.max(0, Math.round(startIndexSV.value - 1));
        } else {
          target = Math.round(progress.value);
        }
        progress.value = withTiming(target, timing);
        runOnJS(setActiveIndex)(target);
      });
  }, [tabCount, timing, setActiveIndex]);

  return { progress, panGesture, pagerAnimatedStyle };
}