import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import {
  View,
  TouchableOpacity,
  Dimensions,
  StyleSheet,
  FlatList,
  Platform,
  TextInput,
  InteractionManager,
} from 'react-native';
import { BugPlay } from 'lucide-react-native';

import CustomText from '@/components/common/CustomText';
import Animated, { useSharedValue, useAnimatedStyle, withSpring } from 'react-native-reanimated';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import * as Clipboard from 'expo-clipboard';
import { showSuccess, showError } from '@/utils/ui/toast';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { RootSiblingPortal } from 'react-native-root-siblings';
import { wp } from '@/utils/ui/screenUtils';

import logManager from '@/utils/core/debug/LogManager';
// import NetworkLogger from 'react-native-network-logger'; // Lazy-loaded when needed

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

const FloatingDebugger = React.memo(() => {
  const [modalVisible, setModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('logs');
  const [logs, setLogs] = useState([]);
  // const [errors, setErrors] = useState([]); // 移除错误页：不再保留独立错误状态
  const [searchQuery, setSearchQuery] = useState('');
  const [debouncedSearchQuery, setDebouncedSearchQuery] = useState('');
  // 日志级别筛选（默认全选）
  const [selectedLevels, setSelectedLevels] = useState({ log: true, warn: true, error: true });
  const toggleLevel = useCallback((lv) => {
    setSelectedLevels((prev) => ({ ...prev, [lv]: !prev[lv] }));
  }, []);
  // 排序：默认与浏览器控制台一致，新日志在下
  const [sortOrder, setSortOrder] = useState('asc');
  // 延迟挂载重内容与网络面板
  const [contentReady, setContentReady] = useState(false);
  const [NetworkLoggerComp, setNetworkLoggerComp] = useState(null);
  // 首帧就绪：避免 Android 上 Modal 初帧子元素在左上角闪烁
  const [panelReady, setPanelReady] = useState(Platform.OS === 'ios');
  // 新增：安全区 insets
  const insets = useSafeAreaInsets();
  useEffect(() => {
    if (!modalVisible) setPanelReady(Platform.OS === 'ios');
  }, [modalVisible]);
  useEffect(() => {
    if (modalVisible && Platform.OS === 'android') {
      requestAnimationFrame(() => setPanelReady(true));
    }
  }, [modalVisible]);
  
  // rAF 批处理更新引用
  const rafIdRef = useRef(null);
  const pendingUpdateRef = useRef(false);
  // 仅启用日志捕获（不在此时订阅）
  useEffect(() => {
    if (typeof logManager.enable === 'function') {
      try { logManager.enable(); } catch (e) {}
    }
  }, []);
  
  // 在面板可见时再同步状态并订阅更新，关闭即取消订阅；同时延迟一帧挂载重内容
  useEffect(() => {
    let mounted = true;
    let unsubscribe = null;

    if (modalVisible) {
      const handle = InteractionManager.runAfterInteractions(() => {
        if (!mounted) return;
        setContentReady(true);
        try {
          setLogs(logManager.getLogs());
          // setErrors(logManager.getErrors()); // 移除错误页
        } catch (e) {}
        unsubscribe = logManager.addListener?.((type) => {
          if (type === 'log' || type === 'error' || type === 'clear') {
            try {
              if (!pendingUpdateRef.current) {
                pendingUpdateRef.current = true;
                rafIdRef.current = requestAnimationFrame(() => {
                  pendingUpdateRef.current = false;
                  setLogs(logManager.getLogs());
                });
              }
            } catch (e) {}
          }
        });
      });
      return () => {
        mounted = false;
        try { handle?.cancel?.(); } catch (e) {}
        try { unsubscribe && unsubscribe(); } catch (e) {}
        // 取消可能的 rAF
        try {
          if (rafIdRef.current) {
            cancelAnimationFrame(rafIdRef.current);
            rafIdRef.current = null;
          }
          pendingUpdateRef.current = false;
        } catch (e) {}
        setContentReady(false);
      };
    }

    // 不可见：确保不订阅，且重内容未就绪
    setContentReady(false);
    return () => { try { unsubscribe && unsubscribe(); } catch (e) {} };
  }, [modalVisible]);
  
  // 搜索防抖
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchQuery(searchQuery);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  // 切到网络 Tab 时再动态加载 UI 组件
  useEffect(() => {
    if (activeTab === 'network' && !NetworkLoggerComp) {
      import('react-native-network-logger')
        .then((mod) => {
          const Comp = mod.default || mod.NetworkLogger || mod;
          setNetworkLoggerComp(() => Comp);
        })
        .catch(() => {});
    }
  }, [activeTab, NetworkLoggerComp]);
  
  // 使用 useMemo 优化过滤逻辑，基于防抖后的搜索词
  const filteredLogs = useMemo(() => {
    const query = debouncedSearchQuery.trim();
    const base = query ? logManager.searchLogs(query) : logs;
    const allOn = selectedLevels.log && selectedLevels.warn && selectedLevels.error;
    const arr = allOn ? base : base.filter(l => selectedLevels[l.type]);
    // 不再在这里 reverse，改用 FlatList inverted 控制方向
    return arr;
  }, [debouncedSearchQuery, logs, selectedLevels]);
  
  // 移除错误过滤逻辑
  // const filteredErrors = useMemo(() => {
  //   if (!debouncedSearchQuery.trim()) return errors;
  //   return logManager.searchErrors(debouncedSearchQuery);
  // }, [debouncedSearchQuery, errors]);
  
  // 使用 Reanimated 共享值替代 Animated.ValueXY
  const translateX = useSharedValue(screenWidth - wp(80));
  const translateY = useSharedValue(wp(100));
  const offsetX = useSharedValue(0);
  const offsetY = useSharedValue(0);
  
  // 缓存屏幕尺寸和边界值（限制在安全区范围内）
  const screenBounds = useMemo(() => ({
    minX: insets.left,
    minY: insets.top,
    maxX: screenWidth - insets.right - wp(60),
    maxY: screenHeight - insets.bottom - wp(60),
  }), [insets]);
  
  // 手势：在 UI 线程更新，避免 JS/Bridge 抖动
  const panGesture = useMemo(() => {
    const minX = screenBounds.minX;
    const minY = screenBounds.minY;
    const maxX = screenBounds.maxX;
    const maxY = screenBounds.maxY;
  
    return Gesture.Pan()
      .onStart(() => {
        offsetX.value = translateX.value;
        offsetY.value = translateY.value;
      })
      .onUpdate((e) => {
        const nx = offsetX.value + e.translationX;
        const ny = offsetY.value + e.translationY;
        translateX.value = Math.max(minX, Math.min(maxX, nx));
        translateY.value = Math.max(minY, Math.min(maxY, ny));
      })
      .onEnd(() => {
        const clampedX = Math.max(minX, Math.min(maxX, translateX.value));
        const clampedY = Math.max(minY, Math.min(maxY, translateY.value));
        translateX.value = withSpring(clampedX, { stiffness: 300, damping: 25, mass: 1 });
        translateY.value = withSpring(clampedY, { stiffness: 300, damping: 25, mass: 1 });
      });
  }, [screenBounds, translateX, translateY, offsetX, offsetY]);
  
  // 动画样式
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: translateX.value }, { translateY: translateY.value }],
  }));

  const handlePress = useCallback(() => {
    setModalVisible(true);
  }, [setModalVisible]);

  

  // 可展开/收起的长文本组件（使用 numberOfLines 限制行数，避免复制大字符串）
  const ExpandableText = React.memo(({ text, style, collapsedLines = 6, threshold = 400 }) => {
    const [expanded, setExpanded] = useState(false);
    const needsToggle = useMemo(() => {
      if (!text) return false;
      // 以字符阈值/行数作为是否显示“展开”判断，避免昂贵计算
      return text.length > threshold || (text.indexOf('\n') !== -1 && text.split('\n').length > collapsedLines);
    }, [text, threshold, collapsedLines]);
    const toggle = useCallback(() => setExpanded(prev => !prev), []);

    return (
      <View>
        <CustomText style={style} numberOfLines={expanded ? undefined : collapsedLines}>{text}</CustomText>
        {needsToggle && (
          <TouchableOpacity onPress={toggle} hitSlop={{ top: Math.round(wp(6)), bottom: Math.round(wp(6)), left: Math.round(wp(6)), right: Math.round(wp(6)) }}>
            <CustomText style={styles.toggleLink}>{expanded ? '收起' : '展开'}</CustomText>
          </TouchableOpacity>
        )}
      </View>
    );
  });

  // 渲染单个日志项的组件（截断长文案）
  const LogItem = React.memo(({ log }) => (
    <View style={[styles.logItem, styles[log.type]]}>
      <View style={styles.logHeader}>
        <CustomText style={styles.logType}>{log.type.toUpperCase()}</CustomText>
        <View style={styles.logHeaderRight}>
          <CustomText style={styles.timestamp}>{log.timestamp}</CustomText>
          <TouchableOpacity
            style={styles.copyButton}
            onPress={() => {
              Clipboard.setStringAsync(String(log.message))
                .then(() => showSuccess('已复制到剪贴板'))
                .catch(() => showError('复制失败'));
            }}
            hitSlop={{ top: Math.round(wp(6)), bottom: Math.round(wp(6)), left: Math.round(wp(6)), right: Math.round(wp(6)) }}
            activeOpacity={0.8}
            accessibilityLabel="复制该条日志"
          >
            <MaterialIcons name="content-copy" size={wp(16)} color="#007AFF" />
          </TouchableOpacity>
        </View>
      </View>
      <ExpandableText text={log.message} style={styles.logMessage} collapsedLines={6} threshold={400} />
    </View>
  ));

  const renderLogItem = useCallback(({ item: log }) => (
    <LogItem log={log} />
  ), []);

  

  const keyExtractor = useCallback((item) => String(item.id), []);
  const maintainPos = useMemo(() => ({ minIndexForVisible: 0, autoscrollToTopThreshold: Math.round(wp(24)) }), []);
  
  // 渲染单个错误项（已移除错误页）
  // const renderErrorItem = useCallback(({ item: error }) => (
  //   <View key={error.id} style={[styles.logItem, styles.error]}>
  //     <View style={styles.logHeader}>
  //       <Text style={styles.logType}>{error.source?.toUpperCase() || 'ERROR'}</Text>
  //       <Text style={styles.timestamp}>{error.timestamp}</Text>
  //     </View>
  //     <ExpandableText text={error.message} style={styles.logMessage} collapsedLines={6} threshold={400} />
  //   </View>
  // ), []);
  
  const renderTabContent = useCallback(() => {
    switch (activeTab) {
      case 'logs':
        return (
          <View style={styles.tabContent}>
            <View style={styles.searchRow}>
              <TextInput
                style={[styles.searchInput, { width: wp(200), margin: 0 }]}
                placeholder="搜索日志..."
                value={searchQuery}
                onChangeText={setSearchQuery}
                clearButtonMode="while-editing"
              />
              <TouchableOpacity
                style={styles.smallCopyButton}
                onPress={() => {
                  try {
                    const lines = filteredLogs.map((log) => `[${log.type.toUpperCase()}] ${log.timestamp} ${typeof log.message === 'string' ? log.message : String(log.message)}`);
                    const text = lines.join('\n');
                    Clipboard.setStringAsync(text)
                      .then(() => showSuccess('已复制当前显示的日志'))
                      .catch(() => showError('复制失败'));
                  } catch (e) {
                    showError('复制失败');
                  }
                }}
                activeOpacity={0.8}
                accessibilityLabel="复制当前显示的日志"
              >
                <MaterialIcons name="content-copy" size={wp(18)} color="#ffffff" />
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.smallClearButton}
                onPress={() => {
                  logManager.clearLogs();
                  setSearchQuery('');
                }}
                activeOpacity={0.8}
              >
                <CustomText style={styles.smallClearButtonText}>清空</CustomText>
              </TouchableOpacity>
            </View>
            <View style={styles.filterRow}>
              {['log','warn','error'].map((lv) => (
                <TouchableOpacity
                  key={lv}
                  onPress={() => toggleLevel(lv)}
                  activeOpacity={0.8}
                  style={[styles.filterChip, selectedLevels[lv] && styles.filterChipActive]}
                >
                  <CustomText style={[styles.filterChipText, selectedLevels[lv] && styles.filterChipTextActive]}>
                    {lv.toUpperCase()}
                  </CustomText>
                </TouchableOpacity>
              ))}
              <View style={{ flex: 1 }} />
              {['asc','desc'].map((order) => (
                <TouchableOpacity
                  key={order}
                  onPress={() => setSortOrder(order)}
                  activeOpacity={0.8}
                  style={[styles.filterChip, sortOrder === order && styles.filterChipActive]}
                >
                  <CustomText style={[styles.filterChipText, sortOrder === order && styles.filterChipTextActive]}>
                    {order === 'asc' ? '时间升序' : '时间倒序'}
                  </CustomText>
                </TouchableOpacity>
              ))}
            </View>
            {!contentReady ? (
              <View style={styles.emptyContainer}><CustomText style={styles.emptyText}>加载中...</CustomText></View>
            ) : (
              filteredLogs.length === 0 ? (
                <View style={styles.emptyContainer}>
                  <CustomText style={styles.emptyText}>
                    {searchQuery ? '未找到匹配的日志' : '暂无日志'}
                  </CustomText>
                </View>
              ) : (
                <FlatList
                  data={filteredLogs}
                  inverted={sortOrder === 'asc'}
                  renderItem={renderLogItem}
                  keyExtractor={keyExtractor}
                  style={styles.scrollContent}
                  removeClippedSubviews={true}
                  maxToRenderPerBatch={4}
                  windowSize={7}
                  initialNumToRender={4}
                  maintainVisibleContentPosition={maintainPos}
                />
              )
            )}
          </View>
        );
      // 移除错误页
      // case 'errors':
      //   return (/* 错误页已删除 */ null);
      case 'network':
        return (
          <View style={styles.tabContent}>
            {!contentReady ? (
              <View style={styles.emptyContainer}><CustomText style={styles.emptyText}>加载中...</CustomText></View>
            ) : NetworkLoggerComp ? (
              <NetworkLoggerComp 
                theme="light"
                sort="desc"
                compact={true}
                maxRequests={100}
              />
            ) : (
              <View style={styles.emptyContainer}><CustomText style={styles.emptyText}>正在加载网络面板...</CustomText></View>
            )}
          </View>
        );
      default:
        return null;
    }
  }, [activeTab, filteredLogs, debouncedSearchQuery, searchQuery, contentReady, NetworkLoggerComp, renderLogItem, sortOrder, selectedLevels]);

  return (
    <>
      {/* 悬浮按钮（提升到 RootSiblingPortal，确保层级最高）*/}
      <RootSiblingPortal>
        <GestureDetector gesture={panGesture}>
          <Animated.View
            style={[
              styles.floatingButton,
              animatedStyle,
            ]}
          >
            <TouchableOpacity
              style={styles.buttonContainer}
              onPress={handlePress}
              
              activeOpacity={0.8}
              hitSlop={{ top: Math.round(wp(12)), bottom: Math.round(wp(12)), left: Math.round(wp(12)), right: Math.round(wp(12)) }}
            >
              <BugPlay color="#fff" size={wp(30)} />
            </TouchableOpacity>
          </Animated.View>
        </GestureDetector>
      </RootSiblingPortal>

      {/* 调试面板覆盖层（非 react-native 的 Modal）*/}
      <RootSiblingPortal>
        {modalVisible && (
          <View style={[styles.overlayRoot, Platform.OS === 'android' && !panelReady && { opacity: 0 }]}>
            <SafeAreaView style={styles.modalContainer} edges={['top']}>
              <View style={styles.header}>
                <CustomText style={styles.title}>调试面板</CustomText>
                <TouchableOpacity
                  style={styles.closeButton}
                  onPress={() => setModalVisible(false)}
                  hitSlop={{ top: Math.round(wp(8)), bottom: Math.round(wp(8)), left: Math.round(wp(8)), right: Math.round(wp(8)) }}
                >
                  <CustomText style={styles.closeButtonText}>✕</CustomText>
                </TouchableOpacity>
              </View>
              <View style={styles.tabBar}>
                {[
                  { key: 'logs', label: '日志' },
                  { key: 'network', label: '网络' },
                ].map(tab => (
                  <TouchableOpacity
                    key={tab.key}
                    style={[
                      styles.tab,
                      activeTab === tab.key && styles.activeTab,
                    ]}
                    onPress={() => setActiveTab(tab.key)}
                  >
                    <CustomText
                      style={[
                        styles.tabText,
                        activeTab === tab.key && styles.activeTabText,
                      ]}
                    >
                      {tab.label}
                    </CustomText>
                  </TouchableOpacity>
                ))}
              </View>
              {renderTabContent()}
            </SafeAreaView>
          </View>
        )}
      </RootSiblingPortal>
    </>
  );
});

const styles = StyleSheet.create({
  overlayRoot: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 2147483647,
  },
  floatingButton: {
    position: 'absolute',
    width: wp(60),
    height: wp(60),
    zIndex: 99999999999,
    // 性能优化
    shouldRasterizeIOS: true,
    renderToHardwareTextureAndroid: true,
  },
  buttonContainer: {
    width: '100%',
    height: '100%',
    borderRadius: wp(30),
    backgroundColor: '#007AFF',
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: wp(2) },
    shadowOpacity: 0.25,
    shadowRadius: wp(4),
    elevation: Platform.OS === 'android' ? Math.round(wp(4)) : 0,
  },
  buttonText: {

    fontSize: wp(24),
  },
  modalContainer: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: wp(10),
    paddingVertical: wp(2),
    borderBottomWidth: wp(1),
    borderBottomColor: '#e0e0e0',
  },
  title: {
    fontSize: wp(14),
    lineHeight: wp(18),
    fontWeight: 'bold',
    color: '#333',
  },
  closeButton: {
    width: wp(24),
    height: wp(24),
    borderRadius: wp(12),
    backgroundColor: '#f0f0f0',
    justifyContent: 'center',
    alignItems: 'center',
  },
  closeButtonText: {
    fontSize: wp(12),
    color: '#666',
  },
  tabBar: {
    flexDirection: 'row',
    backgroundColor: '#f8f8f8',
    paddingHorizontal: wp(8),
  },
  tab: {
    flex: 1,
    paddingVertical: wp(6),
    alignItems: 'center',
  },

  activeTab: {
    borderBottomWidth: wp(1),
    borderBottomColor: '#007AFF',
  },
  tabText: {
    fontSize: wp(14),
    color: '#666',
  },

  activeTabText: {
    color: '#007AFF',
    fontWeight: 'bold',
  },
  tabContent: {
    flex: 1,
  },
  searchInput: {
    height: wp(36),
    borderWidth: wp(1),
    borderColor: '#e0e0e0',
    borderRadius: wp(8),
    paddingHorizontal: wp(12),
    paddingVertical: Platform.OS === 'android' ? 0 : wp(8),
    margin: wp(16),
    backgroundColor: '#f8f9fa',
    fontSize: wp(14),
    textAlignVertical: 'center',
  },
  searchRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: wp(12),
    paddingTop: wp(8),
    gap: wp(6),
  },
  // 日志级别筛选样式
  filterRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: wp(12),
    paddingTop: wp(4),
    paddingBottom: wp(4),
    gap: wp(8),
  },
  filterChip: {
    borderWidth: wp(1),
    borderColor: '#e0e0e0',
    backgroundColor: '#f1f3f5',
    borderRadius: wp(16),
    paddingHorizontal: wp(10),
    paddingVertical: wp(4),
  },
  filterChipActive: {
    borderColor: '#007AFF',
    backgroundColor: '#e6f0ff',
  },
  filterChipText: {
    fontSize: wp(12),
    color: '#666',
  },
  filterChipTextActive: {
    color: '#007AFF',
  },
  smallCopyButton: {
   width: wp(50),
    height: wp(30),
    borderRadius: wp(8),
    backgroundColor: '#007AFF',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: wp(6),
  },
  
  smallClearButton: {
    width: wp(50),
    height: wp(30),
    borderRadius: wp(8),
    backgroundColor: '#dc3545',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: wp(6),
  },
  smallClearButtonText: {
    color: '#fff',
    fontSize: wp(14),
  
  },
  scrollContent: {
    flex: 1,
    paddingHorizontal: wp(16),
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: wp(50),
  },
  emptyText: {
    textAlign: 'center',
    color: '#999',
    fontSize: wp(16),
  },
  logItem: {
    marginBottom: wp(12),
    padding: wp(12),
    borderRadius: wp(8),
    borderLeftWidth: wp(4),
  },
  logHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: wp(4),
  },
  logHeaderRight: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  logType: {
    fontSize: wp(10),
    fontWeight: 'bold',
    color: '#666',
    backgroundColor: '#e9ecef',
    paddingHorizontal: wp(6),
    paddingVertical: wp(2),
    borderRadius: wp(4),
  },
  log: {
    backgroundColor: '#f8f9fa',
    borderLeftColor: '#28a745',
  },
  warn: {
    backgroundColor: '#fff3cd',
    borderLeftColor: '#ffc107',
  },
  error: {
    backgroundColor: '#f8d7da',
    borderLeftColor: '#dc3545',
  },
  timestamp: {
    fontSize: wp(12),
    color: '#666',
    marginBottom: wp(4),
  },
  copyButton: {
    marginLeft: wp(8),
    paddingHorizontal: wp(8),
    paddingVertical: wp(4),
    borderRadius: wp(6),
    backgroundColor: '#e9ecef',
  },
  
  logMessage: {
    fontSize: wp(14),
    color: '#333',
    fontFamily: Platform.OS === 'ios' ? 'Menlo' : 'monospace',
  },
  toggleLink: {
    fontSize: wp(12),
    color: '#007AFF',
    marginTop: wp(6),
  },
  
});

// 导出一个控制器来管理悬浮窗的显示/隐藏
export const FloatingDebuggerController = {
  show: null,
  hide: null,
};

// 包装组件，用于控制显示状态
const FloatingDebuggerWrapper = () => {
  const [isVisible, setIsVisible] = useState(false);
  
  useEffect(() => {
    FloatingDebuggerController.show = () => setIsVisible(true);
    FloatingDebuggerController.hide = () => setIsVisible(false);
    
    // 开发环境下自动显示
    // if (process.env.EXPO_PUBLIC_ENV === 'dev') {
    //   setIsVisible(true);
    // }
    setIsVisible(true);
  }, []);
  
  if (!isVisible) return null;
  return <FloatingDebugger />;
};

export default FloatingDebuggerWrapper;
