/**
 * 关于我们页面 AboutScreen
 * 威友 - 应用信息、版本检查与更新
 * 扁平化设计风格，参考登录、注册、设置页面
 */

import React, { useMemo, useState, useCallback } from 'react';
import {
  View,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
  ActivityIndicator,
  Linking,
  Platform,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import Constants from 'expo-constants';
import { useRouter } from 'expo-router';
import {
  useAppColors,
  spacing,
  fontSizes,
  borderRadius,
  type AppColors,
} from '../../theme';
import { Text } from '../../components/common';
import { useResponsive, useResponsiveSpacing } from '../../hooks';
import { checkForAPKUpdate, type VersionCheckResult } from '@/services/platform';
import * as hrefs from '../../navigation/hrefs';

const CONTENT_MAX_WIDTH = 720;

const THEME_COLORS = {
  primary: '#FF6B35',
  primaryLight: '#FF8C5A',
  primaryDark: '#E55A2B',
};

const APP_NAME = '威友';
const APP_SLOGAN = '连接校园，分享生活';
const APP_VERSION = Constants.expoConfig?.version || '1.0.0';
const BUILD_NUMBER = Constants.expoConfig?.android?.versionCode || Constants.expoConfig?.ios?.buildNumber || '1';

function createAboutStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.paper,
    },
    scrollContent: {
      paddingVertical: spacing.lg,
    },
    content: {
      maxWidth: CONTENT_MAX_WIDTH,
      alignSelf: 'center',
      width: '100%',
    },

    header: {
      alignItems: 'center',
      marginBottom: spacing['3xl'],
      paddingTop: spacing.xl,
    },
    logoContainer: {
      width: 80,
      height: 80,
      borderRadius: 20,
      backgroundColor: THEME_COLORS.primary,
      justifyContent: 'center',
      alignItems: 'center',
      marginBottom: spacing.lg,
    },
    logoText: {
      fontSize: 32,
      fontWeight: '700',
      color: '#fff',
    },
    appName: {
      fontSize: 24,
      fontWeight: '700',
      color: colors.text.primary,
      marginBottom: spacing.xs,
    },
    appSlogan: {
      fontSize: 14,
      color: colors.text.secondary,
      marginBottom: spacing.sm,
    },
    versionText: {
      fontSize: 13,
      color: colors.text.hint,
    },

    groupContainer: {
      marginBottom: spacing['2xl'],
      maxWidth: CONTENT_MAX_WIDTH,
      alignSelf: 'center',
      width: '100%',
    },
    groupHeader: {
      paddingHorizontal: spacing['2xl'],
      marginBottom: spacing.sm,
      marginTop: spacing.sm,
    },
    groupTitle: {
      fontWeight: '600',
      fontSize: fontSizes.sm,
      color: colors.text.secondary,
      textTransform: 'uppercase',
      letterSpacing: 0.5,
    },

    settingItem: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingVertical: 16,
      paddingHorizontal: spacing['2xl'],
      borderBottomWidth: StyleSheet.hairlineWidth,
      borderBottomColor: colors.divider,
    },
    settingItemLast: {
      borderBottomWidth: 0,
    },
    settingItemLeft: {
      flexDirection: 'row',
      alignItems: 'center',
      flex: 1,
    },
    iconContainer: {
      width: 24,
      height: 24,
      justifyContent: 'center',
      alignItems: 'center',
      marginRight: spacing.lg,
    },
    settingContent: {
      flex: 1,
    },
    subtitle: {
      marginTop: 2,
    },

    updateSection: {
      paddingHorizontal: spacing['2xl'],
      marginBottom: spacing['2xl'],
    },
    updateCard: {
      backgroundColor: colors.background.default,
      borderRadius: borderRadius.xl,
      padding: spacing.lg,
    },
    updateHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: spacing.lg,
    },
    updateIconContainer: {
      width: 44,
      height: 44,
      borderRadius: borderRadius.lg,
      backgroundColor: colors.background.paper,
      justifyContent: 'center',
      alignItems: 'center',
      marginRight: spacing.md,
    },
    updateTitle: {
      fontSize: 16,
      fontWeight: '600',
      color: colors.text.primary,
    },
    updateSubtitle: {
      fontSize: 13,
      color: colors.text.secondary,
      marginTop: 2,
    },

    checkUpdateButton: {
      height: 48,
      borderRadius: borderRadius.lg,
      backgroundColor: THEME_COLORS.primary,
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'row',
    },
    checkUpdateText: {
      fontSize: 15,
      fontWeight: '600',
      color: '#fff',
      marginLeft: spacing.sm,
    },

    updateStatusContainer: {
      alignItems: 'center',
      paddingVertical: spacing.lg,
    },
    updateStatusTitle: {
      fontSize: 15,
      fontWeight: '600',
      color: colors.text.primary,
      marginTop: spacing.md,
      marginBottom: spacing.xs,
    },
    updateStatusDesc: {
      fontSize: 13,
      color: colors.text.secondary,
      textAlign: 'center',
    },

    newVersionContainer: {
      backgroundColor: colors.background.paper,
      borderRadius: borderRadius.lg,
      padding: spacing.lg,
      marginTop: spacing.md,
    },
    newVersionHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: spacing.xs,
    },
    newVersionText: {
      fontSize: 15,
      fontWeight: '600',
      color: colors.text.primary,
    },
    newVersionBadge: {
      backgroundColor: THEME_COLORS.primary,
      paddingHorizontal: spacing.sm,
      paddingVertical: 2,
      borderRadius: borderRadius.sm,
      marginLeft: spacing.sm,
    },
    newVersionBadgeText: {
      color: '#fff',
      fontSize: 10,
      fontWeight: '600',
    },
    releaseDate: {
      fontSize: 12,
      color: colors.text.hint,
      marginBottom: spacing.md,
    },
    releaseNotes: {
      fontSize: 14,
      color: colors.text.secondary,
      lineHeight: 20,
      marginBottom: spacing.lg,
    },
    updateActions: {
      flexDirection: 'row',
      gap: spacing.md,
    },
    updateButton: {
      flex: 1,
      height: 40,
      borderRadius: borderRadius.md,
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'row',
    },
    primaryButton: {
      backgroundColor: THEME_COLORS.primary,
    },
    secondaryButton: {
      backgroundColor: colors.background.default,
    },
    primaryButtonText: {
      fontSize: 14,
      fontWeight: '600',
      color: '#fff',
      marginLeft: spacing.xs,
    },
    secondaryButtonText: {
      fontSize: 14,
      fontWeight: '600',
      color: colors.text.primary,
      marginLeft: spacing.xs,
    },

    infoValue: {
      fontSize: 15,
      color: colors.text.secondary,
    },

    footer: {
      alignItems: 'center',
      marginTop: spacing.xl,
      paddingBottom: spacing.xl,
    },
    copyright: {
      fontSize: 12,
      color: colors.text.hint,
      textAlign: 'center',
    },
    companyName: {
      fontSize: 12,
      color: colors.text.hint,
      marginTop: spacing.xs,
    },
  });
}

type UpdateStatus = 'idle' | 'checking' | 'noUpdate' | 'hasUpdate' | 'error' | 'notSupported';

export const AboutScreen: React.FC = () => {
  const colors = useAppColors();
  const styles = useMemo(() => createAboutStyles(colors), [colors]);
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { isMobile } = useResponsive();
  const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });

  const [updateStatus, setUpdateStatus] = useState<UpdateStatus>('idle');
  const [versionInfo, setVersionInfo] = useState<VersionCheckResult | null>(null);
  const [errorMessage, setErrorMessage] = useState('');

  const scrollBottomInset = isMobile ? 64 + 24 + insets.bottom + spacing.md : spacing.md;

  const checkForUpdate = useCallback(async () => {
    setUpdateStatus('checking');
    setErrorMessage('');

    try {
      if (Platform.OS !== 'android') {
        setUpdateStatus('notSupported');
        return;
      }

      const result = await checkForAPKUpdate(true);
      
      if (!result) {
        setErrorMessage('无法获取版本信息，请检查网络连接');
        setUpdateStatus('error');
        return;
      }

      setVersionInfo(result);

      if (result.hasUpdate) {
        setUpdateStatus('hasUpdate');
      } else {
        setUpdateStatus('noUpdate');
      }
    } catch (error) {
      setErrorMessage('检查更新失败，请稍后重试');
      setUpdateStatus('error');
    }
  }, []);

  const handleUpdate = useCallback(() => {
    if (!versionInfo?.downloadUrl) return;

    Alert.alert(
      '更新应用',
      `即将下载版本 ${versionInfo.latestVersion}，是否继续？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '立即更新',
          onPress: async () => {
            try {
              const canOpen = await Linking.canOpenURL(versionInfo.downloadUrl);
              if (canOpen) {
                await Linking.openURL(versionInfo.downloadUrl);
              } else {
                Alert.alert('错误', '无法打开下载链接');
              }
            } catch (error) {
              Alert.alert('错误', '打开下载链接失败');
            }
          },
        },
      ]
    );
  }, [versionInfo]);

  const renderUpdateStatus = () => {
    switch (updateStatus) {
      case 'checking':
        return (
          <View style={styles.updateStatusContainer}>
            <ActivityIndicator size="large" color={THEME_COLORS.primary} />
            <Text style={styles.updateStatusTitle}>正在检查更新...</Text>
          </View>
        );

      case 'noUpdate':
        return (
          <View style={styles.updateStatusContainer}>
            <MaterialCommunityIcons name="check-circle" size={36} color="#4CAF50" />
            <Text style={styles.updateStatusTitle}>已是最新版本</Text>
            <Text style={styles.updateStatusDesc}>当前版本 {APP_VERSION} 已是最新版本</Text>
            <TouchableOpacity
              style={[styles.checkUpdateButton, { marginTop: spacing.lg, backgroundColor: colors.background.paper }]}
              onPress={() => setUpdateStatus('idle')}
            >
              <MaterialCommunityIcons name="refresh" size={18} color={colors.text.primary} />
              <Text style={[styles.checkUpdateText, { color: colors.text.primary }]}>重新检查</Text>
            </TouchableOpacity>
          </View>
        );

      case 'hasUpdate':
        return (
          <View style={styles.newVersionContainer}>
            <View style={styles.newVersionHeader}>
              <Text style={styles.newVersionText}>发现新版本</Text>
              <View style={styles.newVersionBadge}>
                <Text style={styles.newVersionBadgeText}>New</Text>
              </View>
            </View>
            <Text style={styles.releaseDate}>版本 {versionInfo?.latestVersion} · 当前版本 {versionInfo?.currentVersion}</Text>
            <Text style={styles.releaseNotes}>新版本已发布，建议立即更新以获得更好的体验。</Text>
            <View style={styles.updateActions}>
              <TouchableOpacity
                style={[styles.updateButton, styles.secondaryButton]}
                onPress={() => setUpdateStatus('idle')}
              >
                <Text style={styles.secondaryButtonText}>稍后再说</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.updateButton, styles.primaryButton]}
                onPress={handleUpdate}
              >
                <MaterialCommunityIcons name="download" size={16} color="#fff" />
                <Text style={styles.primaryButtonText}>立即更新</Text>
              </TouchableOpacity>
            </View>
          </View>
        );

      case 'error':
        return (
          <View style={styles.updateStatusContainer}>
            <MaterialCommunityIcons name="alert-circle" size={36} color={colors.error.main} />
            <Text style={styles.updateStatusTitle}>检查失败</Text>
            <Text style={styles.updateStatusDesc}>{errorMessage || '请检查网络连接后重试'}</Text>
            <TouchableOpacity
              style={[styles.checkUpdateButton, { marginTop: spacing.lg }]}
              onPress={checkForUpdate}
            >
              <MaterialCommunityIcons name="refresh" size={18} color="#fff" />
              <Text style={styles.checkUpdateText}>重新检查</Text>
            </TouchableOpacity>
          </View>
        );

      case 'notSupported':
        return (
          <View style={styles.updateStatusContainer}>
            <MaterialCommunityIcons name="apple" size={36} color={colors.text.secondary} />
            <Text style={styles.updateStatusTitle}>iOS 平台</Text>
            <Text style={styles.updateStatusDesc}>iOS 用户请前往 App Store 检查更新</Text>
            <TouchableOpacity
              style={[styles.checkUpdateButton, { marginTop: spacing.lg, backgroundColor: colors.background.paper }]}
              onPress={() => setUpdateStatus('idle')}
            >
              <MaterialCommunityIcons name="refresh" size={18} color={colors.text.primary} />
              <Text style={[styles.checkUpdateText, { color: colors.text.primary }]}>重新检查</Text>
            </TouchableOpacity>
          </View>
        );

      default:
        return (
          <TouchableOpacity style={styles.checkUpdateButton} onPress={checkForUpdate}>
            <MaterialCommunityIcons name="update" size={18} color="#fff" />
            <Text style={styles.checkUpdateText}>检查新版本</Text>
          </TouchableOpacity>
        );
    }
  };

  const legalItems = [
    { key: 'terms', icon: 'file-document-outline', title: '用户协议', action: () => router.push(hrefs.hrefProfileTerms()) },
    { key: 'privacy', icon: 'shield-outline', title: '隐私政策', action: () => router.push(hrefs.hrefProfilePrivacy()) },
  ];

  const appInfoItems = [
    { key: 'name', icon: 'information-outline', title: '应用名称', value: APP_NAME },
    { key: 'version', icon: 'tag-outline', title: '版本号', value: `v${APP_VERSION} (${BUILD_NUMBER})` },
  ];

  const renderSettingItem = (item: { key: string; icon: string; title: string; value?: string; action?: () => void }, index: number, total: number, showArrow: boolean = false) => (
    <TouchableOpacity
      key={item.key}
      style={[styles.settingItem, index === total - 1 && styles.settingItemLast]}
      onPress={item.action}
      activeOpacity={0.7}
      disabled={!item.action}
    >
      <View style={styles.settingItemLeft}>
        <View style={styles.iconContainer}>
          <MaterialCommunityIcons name={item.icon as any} size={22} color={colors.text.secondary} />
        </View>
        <View style={styles.settingContent}>
          <Text variant="body" color={colors.text.primary}>
            {item.title}
          </Text>
          {item.value && (
            <Text variant="caption" color={colors.text.secondary} style={styles.subtitle}>
              {item.value}
            </Text>
          )}
        </View>
      </View>
      {showArrow && (
        <MaterialCommunityIcons name="chevron-right" size={20} color={colors.text.hint} />
      )}
      {!showArrow && item.value && (
        <Text style={styles.infoValue}>{item.value}</Text>
      )}
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={styles.container} edges={['bottom']}>
      <ScrollView
        contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding }]}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.content}>
          <View style={styles.header}>
            <Text style={styles.appName}>{APP_NAME}</Text>
            <Text style={styles.appSlogan}>{APP_SLOGAN}</Text>
            <Text style={styles.versionText}>版本 {APP_VERSION}</Text>
          </View>

          <View style={styles.updateSection}>
            <View style={styles.updateCard}>
              <View style={styles.updateHeader}>
                <View style={styles.updateIconContainer}>
                  <MaterialCommunityIcons name="cellphone-arrow-down" size={22} color={THEME_COLORS.primary} />
                </View>
                <View>
                  <Text style={styles.updateTitle}>版本更新</Text>
                  <Text style={styles.updateSubtitle}>检查并获取最新版本</Text>
                </View>
              </View>
              {renderUpdateStatus()}
            </View>
          </View>

          <View style={styles.groupContainer}>
            <View style={styles.groupHeader}>
              <Text variant="caption" style={styles.groupTitle}>
                法律信息
              </Text>
            </View>
            <View>
              {legalItems.map((item, index) => renderSettingItem(item, index, legalItems.length, true))}
            </View>
          </View>

          <View style={styles.groupContainer}>
            <View style={styles.groupHeader}>
              <Text variant="caption" style={styles.groupTitle}>
                应用信息
              </Text>
            </View>
            <View>
              {appInfoItems.map((item, index) => renderSettingItem(item, index, appInfoItems.length, false))}
            </View>
          </View>

          <View style={styles.footer}>
            <Text style={styles.copyright}>© 2026 青春之旅电子信息科技（威海）有限公司</Text>
            <Text style={styles.companyName}>鲁ICP备XXXXXXXX号-1</Text>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default AboutScreen;
