import React from 'react';
import { Pressable, ScrollView, StyleSheet, Text, View, Share, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../theme';
import { useT } from '../i18n';
import { buildErrorRecoveryData, crashReporter } from '../services/crash';
import * as FileSystem from 'expo-file-system/legacy';

interface ErrorBoundaryProps {
  error: Error;
  resetError: () => void;
}

export function ErrorScreen({ error, resetError }: ErrorBoundaryProps) {
  const { theme } = useTheme();
  const t = useT();
  const data = buildErrorRecoveryData(error);

  const clearCacheAndRestart = async () => {
    try {
      const settingsFile = FileSystem.documentDirectory + 'settings.json';
      const metadataFile = FileSystem.documentDirectory + 'metadata.json';
      const settingsInfo = await FileSystem.getInfoAsync(settingsFile);
      if (settingsInfo.exists) await FileSystem.deleteAsync(settingsFile);
      const metadataInfo = await FileSystem.getInfoAsync(metadataFile);
      if (metadataInfo.exists) await FileSystem.deleteAsync(metadataFile);
    } catch {
      // 忽略删除错误
    }
    resetError();
  };

  const exportLogs = async () => {
    try {
      const logs = crashReporter.exportAsText();
      if (!logs) {
        Alert.alert(
          t('error.noLogs') || '提示', 
          t('error.noLogsMsg') || '暂无崩溃日志记录'
        );
        return;
      }
      await Share.share({
        message: logs,
        title: 'Bean Mobile Crash Logs',
      });
    } catch (e) {
      Alert.alert(
        t('error.exportFail') || '导出失败', 
        e instanceof Error ? e.message : String(e)
      );
    }
  };

  return (
    <SafeAreaView style={[styles.page, { backgroundColor: theme.colors.bgPrimary }]}>
      <ScrollView contentContainerStyle={styles.content}>
        <View style={[styles.iconWrap, { backgroundColor: theme.colors.bgTertiary }]}>
          <Ionicons name="warning" size={64} color={theme.colors.error} />
        </View>
        <Text style={[theme.typography.h2, { color: theme.colors.fgPrimary, marginTop: 16, textAlign: 'center' }]}>
          {data.title}
        </Text>
        <Text style={[theme.typography.body, { color: theme.colors.fgSecondary, marginTop: 8, textAlign: 'center' }]}>
          {data.message}
        </Text>
        {data.stack && (
          <View style={[styles.stackBox, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border }]}>
            {/* monospace 有意保留：堆栈文本需要等宽对齐（P5 审计允许项） */}
            <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, fontFamily: 'monospace' }]} numberOfLines={10}>
              {data.stack}
            </Text>
          </View>
        )}
        <View style={styles.actions}>
          <Pressable
            onPress={resetError}
            style={({ pressed }) => [styles.btn, { backgroundColor: theme.colors.accent, opacity: pressed ? 0.7 : 1 }]}
          >
            <Text style={{ color: theme.colors.fgInverse, fontWeight: '700' }}>
              {t('error.retry') || '重试'}
            </Text>
          </Pressable>
          <Pressable
            onPress={clearCacheAndRestart}
            style={({ pressed }) => [styles.btn, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border, borderWidth: 1, opacity: pressed ? 0.7 : 1 }]}
          >
            <Text style={{ color: theme.colors.fgPrimary }}>
              {t('error.clearCache') || '清除缓存并重启'}
            </Text>
          </Pressable>
          <Pressable
            onPress={exportLogs}
            style={({ pressed }) => [styles.btn, { backgroundColor: theme.colors.bgTertiary, borderColor: theme.colors.border, borderWidth: 1, opacity: pressed ? 0.7 : 1 }]}
          >
            <Text style={{ color: theme.colors.fgPrimary }}>
              {t('error.exportLogs') || '导出日志'}
            </Text>
          </Pressable>
        </View>
        <Text style={[theme.typography.caption, { color: theme.colors.fgSecondary, marginTop: 24, textAlign: 'center' }]}>
          {t('error.subTitle') || '如果问题持续出现，请导出日志并提交至 GitHub'}
        </Text>
      </ScrollView>
    </SafeAreaView>
  );
}

export default function ErrorBoundary({ error, resetError }: ErrorBoundaryProps) {
  return <ErrorScreen error={error} resetError={resetError} />;
}

const styles = StyleSheet.create({
  page: { flex: 1 },
  content: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24 },
  iconWrap: { width: 100, height: 100, borderRadius: 50, alignItems: 'center', justifyContent: 'center' },
  stackBox: { width: '100%', marginTop: 16, padding: 12, borderRadius: 8, borderWidth: 1, maxHeight: 200 },
  actions: { marginTop: 24, gap: 10, width: '100%' },
  btn: { width: '100%', paddingVertical: 14, borderRadius: 12, alignItems: 'center' },
});
