
import React, { useEffect, useMemo, useRef, useState, useCallback, memo } from 'react';
import { StyleSheet, Image, Pressable, Platform } from 'react-native';
import CustomText from '@/components/common/CustomText.jsx';
import { Image as ExpoImage } from 'expo-image';
import * as ReactNative from 'react-native';
import { View } from 'tamagui';
import { wp } from '@/utils/ui/screenUtils';
import Svg, { Path, Circle } from 'react-native-svg';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, runOnJS, withRepeat, Easing, useAnimatedProps, withSequence, withDelay } from 'react-native-reanimated';
import { router } from 'expo-router';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import * as Haptics from 'expo-haptics';
import { multiCheckAuth } from '@/api/approve';
import ReportModal from '@/components/toolbox/ReportModal';
import { useTranslation } from '@/node_modules/react-i18next';
import {CustomHeader} from '@/components/common/CustomHeader';
import { useTabBarHeight } from '@/hooks/useTabBarHeight';
import { useToolboxStore,useAppStore } from '@/stores';
import runtimeConfig from '@/utils/core/runtimeConfig'
const AnimatedPath = Animated.createAnimatedComponent(Path);
const { primary } = useAppStore.getState()
const COLORS = ['#9F3165', primary];
const EDGE_STROKE_W = 1.2; // 外圈描边参数
const EDGE_INSET = EDGE_STROKE_W / 2; // 内缩半个描边宽度
const EDGE_EPS_DEG = 0.1; // 收缩端点角度，减小以保持连续性
const deg2rad = (deg) => (deg * Math.PI) / 180;
const polarToCartesian = (cx, cy, r, angleInDeg) => {
  const a = deg2rad(angleInDeg);
  return {
    x: cx + r * Math.cos(a),
    y: cy + r * Math.sin(a),
  };
};


// 通过 key -> 静态资源映射派生 icon（require 需静态路径）
const ICON_MAP = {
  t1: require('@/assets/images/toolbox/znkp.png'),
  t2: require('@/assets/images/toolbox/1056_15.png'),
  t3: require('@/assets/images/toolbox/report.png'),
  t4: require('@/assets/images/toolbox/checkIn.png'),
};

// 生成扇形路径（start/end 角度，角度为数学极坐标，0°在 x 轴正向，逆时针为正）
const describeArc = (cx, cy, r, startAngle, endAngle) => {
  const start = polarToCartesian(cx, cy, r, startAngle);
  const end = polarToCartesian(cx, cy, r, endAngle);
  const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1';
  const d = [
    'M', start.x, start.y,
    'A', r, r, 0, largeArcFlag, 1, end.x, end.y,
    'L', cx, cy,
    'Z',
  ].join(' ');
  return d;
};

// 仅外圈弧线（用于描边）
const describeArcEdge = (cx, cy, r, startAngle, endAngle) => {
  const start = polarToCartesian(cx, cy, r, startAngle);
  const end = polarToCartesian(cx, cy, r, endAngle);
  const largeArcFlag = endAngle - startAngle <= 180 ? '0' : '1';
  return ['M', start.x, start.y, 'A', r, r, 0, largeArcFlag, 1, end.x, end.y].join(' ');
};

// 扇形标签组件
const ToolSlot = memo(function ToolSlot({ containerStyle, icon, name }) {
  return (
    <View style={[{ position: 'absolute', alignItems: 'center', justifyContent: 'center' }, containerStyle]} pointerEvents="none">
      <ReactNative.View
        style={{
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Image source={icon} style={{ width: wp(24), height: wp(24), marginBottom: wp(6) }} />
      </ReactNative.View>
      <CustomText
        style={{
          color: '#fff',
          fontSize: wp(12),
          textAlign: 'center',
          maxWidth: wp(64),
        }}
        numberOfLines={1}
        ellipsizeMode="tail"
      >
        {name}
      </CustomText>
    </View>
  );
});

const HighlightOverlay = memo(({ path, edgePath, style }) => {
  return (
    <Animated.View style={[StyleSheet.absoluteFill, style]} pointerEvents="none">
      <Svg style={StyleSheet.absoluteFill}>
        <Path d={path} fill="#FFFFFF" fillOpacity={0.2} />
        <Path
          d={edgePath}
          fill="none"
          stroke="rgba(255,255,255,0.5)"
          strokeWidth={1.5}
          strokeLinecap="butt"
          strokeLinejoin="round"
        />
      </Svg>
    </Animated.View>
  );
});

export default function ToolboxScreen() {
  const { t } = useTranslation('toolbox');
  const { tools, addTools } = useToolboxStore();
  const [showReportModal, setShowReportModal] = useState(false);

  // 点击扇形逻辑（保持 routeMap 写法）：支持按 key 或 name 触发
  const routeMap = {
    t1: (tool, index) => router.push({ pathname: '/webview', params: { url: `${runtimeConfig.EXPO_PUBLIC_KAOPEI_URL}/#/` } }),
    t2: (tool, index) => {
    router.push({ pathname: '/webview', params: { url: `${runtimeConfig.EXPO_PUBLIC_XIAOMO_URL}/#/` } });
       // router.push({ pathname: '/webview', params: { url: 'http://192.168.88.102:9000/#/' } });
    },
    t3: (tool, index) => setShowReportModal(true),
    t4: (tool, index) => router.push({ pathname: '/webview', params: { url: `${process.env.EXPO_PUBLIC_H5_APPROVAL_URL}/#/pages/Toolbox/venueSign` } }),
  };
  // 兼容名称触发（按当前语言的文案以及历史中文文案）
  const routeMapByName = {
    [t('names.meetingManage')]: routeMap.t1,
    [t('names.xiaomo')]: routeMap.t2,
    [t('names.bossWeekly')]: routeMap.t3,
    [t('names.venueSign')]: routeMap.t4,
  };
  const routeMapByZhName = {
    '会议管理': routeMap.t1,
    '小墨': routeMap.t2,
    '总监周报': routeMap.t3,
    '会场签到': routeMap.t4,
  };
  const onSelect = useCallback((tool, index) => {
    const fn = routeMap[tool?.key] ?? routeMapByZhName[tool?.name] ?? routeMapByName[tool?.name];
    if (fn) fn(tool, index);
  }, []);
  const getMultiCheckAuth = useCallback(async () => {
    try {
      const url_boss = 'seller_report_boss_auth';
      const url_checkIn = 'app-checkIn';
      const res = await multiCheckAuth({
        checkList: [
          { type: 'button', url: url_boss },
          { type: 'button', url: url_checkIn },
        ],
      });
      if (res.status === 0 && Array.isArray(res.data?.checkList)) {
        const toAdd = [];
        for (const item of res.data.checkList) {
          if (item.url === url_boss && item.result) {
            toAdd.push({ key: 't3', name: '总监周报' });
          }
          if (item.url === url_checkIn && item.result) {
            toAdd.push({ key: 't4', name: '会场签到' });
          }
        }
        if (toAdd.length > 0) {
          addTools(toAdd);
        }
      }
    } catch (e) {
      console.warn('multiCheckAuth failed', e);
    }
  }, [addTools]);

  useEffect(() => {
    getMultiCheckAuth();
  }, [getMultiCheckAuth]);

  const width375 = wp(375);
  const radius = wp(160);
  const wheelHeight = radius;
  const EXTRA_CROP_SPACE = wp(40); // 增加顶部空间防止点击放大时被裁剪

  // 整圆分段：>3 固定 6 等分；<=3 时为 2/4/6 等分
  const slotsCountFull = tools.length > 3 ? 6 : (tools.length === 0 ? 6 : tools.length * 2);
  const anglePer = 360 / slotsCountFull;

  // 根据工具数量限制滚动步数（每步=一个扇形）
  const scrollLimitSteps = useMemo(() => {
    // 6 个工具自由旋转；其余数量启用阻尼与回弹的有限滚动
    if (tools.length >= 6) return null;
    if (tools.length === 5) return 2;
    if (tools.length === 4) return 1;
    if (tools.length === 3) return 0.5; // 轻微阻尼，回弹到初始位置
    if (tools.length === 2) return 0.01; // 轻微阻尼，回弹到初始位置
    if (tools.length === 1) return 0.5; // 轻微阻尼，回弹到初始位置
    return 0; // 无工具时不滚动
  }, [tools.length]);
  const canScroll = scrollLimitSteps !== 0;
  const LIMIT_DEG = useMemo(() => (scrollLimitSteps == null ? null : scrollLimitSteps * anglePer), [scrollLimitSteps, anglePer]);
  // 有限滚动时：仅允许从右往左（负向）滚动，范围 [-LIMIT_DEG, 0]
  const MIN_DEG = useMemo(() => (LIMIT_DEG == null ? null : -LIMIT_DEG), [LIMIT_DEG]);
  const MAX_DEG = 0;

  // 记录当前按下的扇形索引（SharedValue 替代 State 以避免重渲染）
  const pressedIndexSV = useSharedValue(-1);
  const TAP_SLOP_PX = 8;
  const tapStartRef = useRef({ x: 0, y: 0, t: 0, sx: 0, sy: 0 }); // 记录屏幕坐标
  const panCancelRef = useRef(false);
  const pressAlpha = useSharedValue(0);
  const pressScale = useSharedValue(1);
  const highlightRotationSV = useSharedValue(0);

  // 持久旋转，优化流畅度
  const rotation = useSharedValue(0);
  const startRotation = useSharedValue(0);
  const lastTickAngle = useSharedValue(0);
  const lastTickTime = useSharedValue(0);
  const tickIntervalDeg = 15; // 减小触觉反馈间隔，增加流畅感
  const ROTATE_SENSITIVITY = 1.5; // 提高旋转灵敏度，让更容易转动
  
  // 工具数为 1/2/3 时禁止滚动，强制回到初始位置，避免出现空白扇形
  useEffect(() => {
    if (scrollLimitSteps === 0) {
      rotation.value = withTiming(0, { duration: 160 });
    }
  }, [scrollLimitSteps]);
  // 箭头动效
  const arrowOpacity = useSharedValue(1);
  const arrowTranslateY = useSharedValue(0);
  useEffect(() => {
    arrowOpacity.value = withRepeat(
      withTiming(0.35, { duration: 900, easing: Easing.inOut(Easing.quad) }),
      -1,
      true
    );
    arrowTranslateY.value = withRepeat(
      withTiming(wp(6), { duration: 900, easing: Easing.inOut(Easing.quad) }),
      -1,
      true
    );
  }, []);
  const arrowStyle = useAnimatedStyle(() => ({
    opacity: arrowOpacity.value,
    transform: [{ translateY: arrowTranslateY.value }],
  }));

  const hapticTick = () => {
    if (Platform.OS === 'ios') {
      Haptics.selectionAsync();
    }
  };

  const cx = width375 / 2;
  const cy = radius;
  const innerRadius = wp(26);

  const cancelHighlight = () => {
    panCancelRef.current = true;
  };

  const handleSelect = (index) => {
    if (index >= 0 && index < tools.length) {
      const tool = tools[index];
      if (tool) {
        onSelect(tool, index);
      }
    }
  };

  // 计算点击位置对应的扇形索引
  const calculateTargetIndex = (x, y) => {
    'worklet';
    const dx = x - cx;
    const dy = y - cy;
    const dist = Math.sqrt(dx * dx + dy * dy);

    // 忽略中心白点和外部区域
    if (dist < innerRadius || dist > radius) {
      return -1;
    }

    const angle = Math.atan2(dy, dx) * 180 / Math.PI;
    const effectiveAngle = angle - rotation.value;
    let normAngle = effectiveAngle % 360;
    if (normAngle <= -180) normAngle += 360;
    if (normAngle > 180) normAngle -= 360;

    const i = Math.floor((normAngle + 180) / anglePer);
    let targetIndex = i % slotsCountFull;
    if (targetIndex < 0) targetIndex += slotsCountFull;
    
    return targetIndex;
  };

  const tapGesture = Gesture.Tap()
    .maxDistance(20)
    .onEnd((e) => {
      const targetIndex = calculateTargetIndex(e.x, e.y);
      if (targetIndex !== -1) {
        // 触觉反馈
        runOnJS(hapticTick)();

        // 确保高亮角度正确
        const midAngle = -180 + targetIndex * anglePer + anglePer / 2;
        highlightRotationSV.value = midAngle;

        // 视觉反馈：两段式（选中 -> 确认闪烁 -> 消失）
        // 此时已经是按下状态（opacity 约 0.6），点击时瞬间变全亮(1.0)表示确认，然后淡出
        pressAlpha.value = withSequence(
          withTiming(1, { duration: 50, easing: Easing.out(Easing.quad) }), 
          withTiming(0, { duration: 600, easing: Easing.out(Easing.quad) })
        );
        // 取消缩放动画，保持稳重
        pressScale.value = withTiming(1, { duration: 200 });

        runOnJS(handleSelect)(targetIndex);
      }
    });

  const panGesture = Gesture.Pan()
    .enabled(canScroll)
    .minDistance(0)
    .onStart((e) => {
      runOnJS(cancelHighlight)();
      startRotation.value = rotation.value;
      lastTickAngle.value = rotation.value;

      const targetIndex = calculateTargetIndex(e.x, e.y);
      pressedIndexSV.value = targetIndex;

      if (targetIndex !== -1) {
        // 计算高亮扇形的旋转角度
        const midAngle = -180 + targetIndex * anglePer + anglePer / 2;
        highlightRotationSV.value = midAngle;
        
        // 按下效果：半透明高亮，不缩放
        pressAlpha.value = withTiming(0.6, { duration: 80 });
        pressScale.value = withTiming(1, { duration: 80 });
      }
    })
    .onChange((e) => {
      // 拖动超过阈值取消高亮
      if (pressedIndexSV.value !== -1 && (Math.abs(e.translationX) > 10 || Math.abs(e.translationY) > 10)) {
        pressedIndexSV.value = -1;
        pressAlpha.value = withTiming(0, { duration: 100 });
        pressScale.value = withTiming(1, { duration: 100 });
      }

      const deltaDeg = ((e.translationX / radius) * (180 / Math.PI)) * ROTATE_SENSITIVITY;
      const rawNext = startRotation.value + deltaDeg;
      let nextDeg = rawNext;
      if (LIMIT_DEG != null) {
        if (rawNext < MIN_DEG) {
          const overshoot = rawNext - MIN_DEG;
          nextDeg = MIN_DEG + overshoot * 0.15;
        } else if (rawNext > MAX_DEG) {
          const overshoot = rawNext - MAX_DEG;
          nextDeg = MAX_DEG + overshoot * 0.15;
        }
      }
      rotation.value = nextDeg;

      const diff = Math.abs(rotation.value - lastTickAngle.value);
      const now = Date.now();
      if (diff >= tickIntervalDeg && (now - lastTickTime.value > 50)) {
        lastTickAngle.value = rotation.value;
        lastTickTime.value = now;
        runOnJS(hapticTick)();
      }
    })
    .onEnd((e) => {
      // 移除原有的点击触发逻辑，交给 Tap 手势处理
      // 仅重置高亮状态
      if (pressedIndexSV.value !== -1) {
        // 如果没有触发 Tap (例如长按后松手但没移动)，也做个淡出
        pressAlpha.value = withTiming(0, { duration: 200 });
        pressScale.value = withTiming(1, { duration: 200 });
        pressedIndexSV.value = -1;
      }

      let snapped = Math.round(rotation.value / anglePer) * anglePer;
      if (LIMIT_DEG != null) {
        snapped = Math.max(MIN_DEG, Math.min(MAX_DEG, snapped));
      }
      const velocity = Math.abs(e.velocityX);
      const duration = Math.max(120, Math.min(300, 300 - velocity * 0.1));
      rotation.value = withTiming(snapped, {
        duration,
        easing: Easing.out(Easing.cubic),
      });
    });

  const gesture = Gesture.Simultaneous(panGesture, tapGesture);

  // 移除旧的点击处理函数
  // tapSlot, onTouchStart, onTouchEnd 不再需要


  const rotateStyle = useAnimatedStyle(() => ({
    transform: [{ rotate: `${rotation.value}deg` }],
  }));

  const highlightStyle = useAnimatedStyle(() => ({
    opacity: pressAlpha.value,
    transform: [
      { rotate: `${highlightRotationSV.value}deg` },
      { scale: pressScale.value }
    ],
  }));

  const templatePaths = useMemo(() => {
    // 生成一个以 0 度（3点钟方向）为中心的标准扇形模板
    // start = -anglePer/2, end = anglePer/2
    const start = -anglePer / 2;
    const end = anglePer / 2;
    const path = describeArc(cx, cy, radius, start, end);
    const edgePath = describeArcEdge(cx, cy, radius - EDGE_INSET, start + EDGE_EPS_DEG, end - EDGE_EPS_DEG);
    return { path, edgePath };
  }, [anglePer, cx, cy, radius]);

  const arcsData = useMemo(() => {
    const arr = [];
    for (let i = 0; i < slotsCountFull; i += 1) {
      const start = -180 + i * anglePer;
      const end = start + anglePer;
      const mid = start + anglePer / 2;
      // 确保扇形完全连接，不留间隙
      const path = describeArc(cx, cy, radius, start, end);
      const edgePath = describeArcEdge(cx, cy, radius - EDGE_INSET, start + EDGE_EPS_DEG, end - EDGE_EPS_DEG);
      const baseFill = COLORS[i % 2];
      // 标签位置
      const r = radius * 0.7;
      const p = polarToCartesian(cx, cy, r, mid);
      const box = wp(72);
      const containerStyle = {
        left: p.x - box / 2,
        top: p.y - box / 2,
        width: box,
        height: box,
        transform: [{ rotate: `${mid + 90}deg` }],
      };
      arr.push({ i, start, end, mid, path, edgePath, baseFill, containerStyle });
    }
    return arr;
  }, [slotsCountFull, anglePer, cx, cy, radius]);

  // 每个扇形对应 0..slotsCountFull-1 的一个索引；>3 时一个扇形对应一条；不足 6 的为空
  const getItemForSector = useCallback((i) => {
    if (tools.length === 0) return null;
    if (tools.length <= 3) {
      const mapUpperIndices = {
        1: [0],
        2: [0, 1],
        3: [0, 1, 2],
      };
      const idxs = mapUpperIndices[tools.length];
      const pos = idxs.indexOf(i);
      return pos !== -1 ? tools[pos] : null;
    }
    return i < tools.length ? tools[i] : null;
  }, [tools]);

  // 预生成标签模型，稳定 ToolSlot 的 props 引用
  const slotModels = useMemo(() => {
    return arcsData.map(({ i, containerStyle }) => {
      const item = getItemForSector(i);
      if (!item) return null;
      const icon = ICON_MAP[item.key];
      if (!icon) return null; // 未映射则跳过
      // 按 key 映射到当前语言名称，回退到原存储名称
      const nameByKey = {
        t1: t('names.meetingManage'),
        t2: t('names.xiaomo'),
        t3: t('names.bossWeekly'),
        t4: t('names.venueSign'),
      };
      const displayName = nameByKey[item.key] ?? item.name;
      return { 
        key: `label-${i}`, 
        containerStyle, 
        icon,
        name: displayName, 
      };
    });
  }, [arcsData, getItemForSector, t]);

  const tabBarHeight = useTabBarHeight();
  return (
    <View flex={1} style={{ position: 'relative' }}>
      <ExpoImage
        source={require('@/assets/images/backgrounds/bg6099.webp')}
        style={StyleSheet.absoluteFill}
        contentFit="cover"
        transition={0}
        pointerEvents="none"
        cachePolicy="memory-disk"
      />

      {/* 顶部标题区 */}
      <CustomHeader  headerShown={false} />
      <View style={{ position: 'absolute', top: wp(148), left: 0, right: 0, alignItems: 'center' }}>
        <CustomText style={{ color: '#fff', fontSize: wp(28), marginBottom: wp(26) }}>{t('common:tabs.toolbox')}</CustomText>
        <Animated.View style={arrowStyle}>
          <Image source={require('@/assets/images/toolbox/5933.png')} style={{ width: wp(44.94), height: wp(22.11) }} />
        </Animated.View>
      </View>

      {/* 半圆转盘（整圆旋转，仅露出上半） */}
      <View
        style={[
          styles.wheelContainer,
          {
            height: wheelHeight + EXTRA_CROP_SPACE,
            bottom: tabBarHeight,
            paddingTop: EXTRA_CROP_SPACE,
          },
        ]}
      >
        <GestureDetector gesture={gesture}> 
          <Animated.View style={{ width: width375, height: radius * 2 }}>
            <Animated.View style={[{ width: width375, height: radius * 2, marginTop: 0 }, rotateStyle]}> 
              <Svg width={width375} height={radius * 2} viewBox={`0 0 ${width375} ${radius * 2}`}>
                {arcsData.map(({ i, path, baseFill }) => (
                  <React.Fragment key={`seg-${i}`}>
                    <Path
                      d={path}
                      fill={baseFill}
                      pointerEvents="none"
                    />
                  </React.Fragment>
                ))}
                {/* 中心白点 */}
                <Circle cx={cx} cy={cy} r={wp(26)} fill="#fff" pointerEvents="none" />
              </Svg>

              {/* 独立的高亮层，不参与 SVG 内部渲染循环 */}
              <HighlightOverlay
                path={templatePaths.path}
                edgePath={templatePaths.edgePath}
                style={highlightStyle}
              />

              {/* 标签/图标（空扇形跳过渲染） */}
              {slotModels.map((m) => {
                if (!m) return null;
                return (
                  <ToolSlot
                    key={m.key}
                    containerStyle={m.containerStyle}
                    icon={m.icon}
                    name={m.name}
                  />
                );
              })}
            </Animated.View>
          </Animated.View>
        </GestureDetector>
      </View>

      {/* 总监周报弹窗 */}
      <ReportModal visible={showReportModal} onClose={() => setShowReportModal(false)} />
    </View>
  );
}

const styles = StyleSheet.create({
  wheelContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
    alignItems: 'center',
    justifyContent: 'flex-start',
    overflow: 'hidden',
  },
  slot: {
    position: 'absolute',
    alignItems: 'center',
    justifyContent: 'center',
  },
  toolName: {
    color: '#fff',
    fontSize: wp(12),
  },
  // 移除未使用的模态相关样式（由 ReportModal 自身实现）
  // modalOverlay: { ... },
  // modalCard: { ... },
  // modalTitle: { ... },
  // modalRow: { ... },
  // modalRowText: { ... },
});