import React, { useMemo } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import logManager from '@/utils/core/debug/LogManager';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 记录错误到日志管理器
    logManager.addError('react', [
      `React Error: ${error.message}`,
      `Component Stack: ${errorInfo.componentStack}`,
      `Error Stack: ${error.stack}`
    ]);
    
    this.setState({
      error,
      errorInfo
    });
    
    // 如果有自定义错误处理函数，调用它
    if (this.props.onError) {
      this.props.onError(error, errorInfo);
    }
  }

  handleRetry = () => {
    this.setState({ hasError: false, error: null, errorInfo: null });
  };

  render() {
    if (this.state.hasError) {
      // 如果有自定义错误 UI，使用它
      if (this.props.fallback) {
        return this.props.fallback(this.state.error, this.state.errorInfo, this.handleRetry);
      }
      
      // 默认错误 UI
      return (
        <ErrorUI 
          error={this.state.error}
          errorInfo={this.state.errorInfo}
          onRetry={this.handleRetry}
        />
      );
    }

    return this.props.children;
  }
}

const styles = StyleSheet.create({
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#fff',
  },
  errorTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#dc3545',
    marginBottom: 16,
  },
  errorMessage: {
    fontSize: 16,
    color: '#666',
    textAlign: 'center',
    marginBottom: 20,
    lineHeight: 24,
  },
  debugInfo: {
    backgroundColor: '#f8f9fa',
    padding: 16,
    borderRadius: 8,
    marginBottom: 20,
    width: '100%',
    maxHeight: 200,
  },
  debugTitle: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  debugText: {
    fontSize: 12,
    color: '#666',
    fontFamily: 'monospace',
  },
  retryButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
  },
  retryButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

// 优化的错误 UI 组件
const ErrorUI = React.memo(({ error, errorInfo, onRetry }) => {
  const errorMessage = useMemo(() => error?.message || '未知错误', [error]);
  const componentStack = useMemo(() => errorInfo?.componentStack, [errorInfo]);
  const isDev = useMemo(() => process.env.EXPO_PUBLIC_ENV === 'dev', []);
  
  return (
    <View style={styles.errorContainer}>
      <Text style={styles.errorTitle}>😵 出错了</Text>
      <Text style={styles.errorMessage}>
        {errorMessage}
      </Text>
      
      {isDev && (
        <View style={styles.debugInfo}>
          <Text style={styles.debugTitle}>调试信息:</Text>
          <Text style={styles.debugText}>
            {componentStack}
          </Text>
        </View>
      )}
      
      <TouchableOpacity style={styles.retryButton} onPress={onRetry}>
        <Text style={styles.retryButtonText}>重试</Text>
      </TouchableOpacity>
    </View>
  );
});

export default ErrorBoundary;