/**
 * 通知设置页 NotificationSettingsScreen（响应式适配）
 * 威友 - 通知相关设置
 * 在宽屏下居中显示
 */

import React, { useState, useEffect, useMemo } from 'react';
import {
  View,
  StyleSheet,
  Switch,
  ScrollView,
  Alert,
  TouchableOpacity,
  Platform,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { spacing, borderRadius, fontSizes, useAppColors, type AppColors } from '../../theme';
import { Text } from '../../components/common';
import {
  loadNotificationPreferences,
  setPushNotificationsPreference,
  setSoundPreference,
  setVibrationPreference,
  jpushService,
} from '@/services/notification';
import { useResponsive, useResponsiveSpacing } from '../../hooks';
import { backgroundSyncManager, BackgroundSyncMode } from '@/services/background';

// 内容最大宽度
const CONTENT_MAX_WIDTH = 720;

interface NotificationSettingItem {
  key: string;
  title: string;
  subtitle?: string;
  icon: string;
  value: boolean;
  onValueChange: (value: boolean) => void;
}

export const NotificationSettingsScreen: React.FC = () => {
  const colors = useAppColors();
  const styles = useMemo(() => createNotificationSettingsStyles(colors), [colors]);
  const [vibrationEnabled, setVibrationEnabledState] = useState(true);
  const [pushEnabled, setPushEnabled] = useState(true);
  const [soundEnabled, setSoundEnabled] = useState(true);
  const [syncMode, setSyncMode] = useState<BackgroundSyncMode>(BackgroundSyncMode.BATTERY_SAVER);
  const [systemPushEnabled, setSystemPushEnabled] = useState<boolean | null>(null);
  const { isWideScreen, isMobile } = useResponsive();
  const insets = useSafeAreaInsets();
  
  // 底部间距，避免被 TabBar 遮挡
  const scrollBottomInset = isMobile ? 64 + 24 + insets.bottom + spacing.md : spacing.md;

  // 加载设置（与启动时 hydrate 一致，避免从其它入口进页时 UI 与内存不一致）
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const prefs = await loadNotificationPreferences();
        setVibrationEnabledState(prefs.vibrationEnabled);
        setPushEnabled(prefs.pushEnabled);
        setSoundEnabled(prefs.soundEnabled);
        setSyncMode(backgroundSyncManager.getMode());

        if (Platform.OS !== 'web') {
          const enabled = await jpushService.checkNotificationPermission();
          setSystemPushEnabled(enabled);
        }
      } catch (error) {
        console.error('加载通知设置失败:', error);
      }
    };
    loadSettings();
  }, []);

  const toggleVibration = async (value: boolean) => {
    try {
      setVibrationEnabledState(value);
      await setVibrationPreference(value);
    } catch (error) {
      console.error('保存震动设置失败:', error);
    }
  };

  const togglePush = async (value: boolean) => {
    try {
      setPushEnabled(value);
      await setPushNotificationsPreference(value);
    } catch (error) {
      console.error('保存推送开关失败:', error);
    }
  };

  const toggleSound = async (value: boolean) => {
    try {
      setSoundEnabled(value);
      await setSoundPreference(value);
    } catch (error) {
      console.error('保存提示音设置失败:', error);
    }
  };

  const handleSyncModeChange = async (mode: BackgroundSyncMode) => {
    if (mode === BackgroundSyncMode.REALTIME) {
      Alert.alert(
        '实时模式',
        '实时模式会在通知栏显示常驻通知以保持应用后台运行，确保消息即时同步。\n\n' +
        '建议在系统设置中将应用加入电池优化白名单以获得最佳效果。\n\n' +
        '注意：此模式可能增加电池消耗。',
        [
          { text: '取消', style: 'cancel' },
          {
            text: '开启',
            onPress: async () => {
              await backgroundSyncManager.setMode(mode);
              setSyncMode(mode);
            },
          },
        ]
      );
    } else {
      await backgroundSyncManager.setMode(mode);
      setSyncMode(mode);
    }
  };

  const syncModeOptions: { mode: BackgroundSyncMode; title: string; subtitle: string; icon: string }[] = [
    {
      mode: BackgroundSyncMode.BATTERY_SAVER,
      title: '省电模式',
      subtitle: '系统后台任务，每 15 分钟检查一次',
      icon: 'leaf',
    },
    {
      mode: BackgroundSyncMode.REALTIME,
      title: '实时模式',
      subtitle: '通知栏常驻保活，即时同步消息',
      icon: 'lightning-bolt',
    },
    {
      mode: BackgroundSyncMode.DISABLED,
      title: '禁用',
      subtitle: '仅在应用打开时接收消息',
      icon: 'close-circle-outline',
    },
  ];

  const handleRequestSystemPermission = async () => {
    if (Platform.OS === 'web') return;
    const granted = await jpushService.requestNotificationPermission();
    setSystemPushEnabled(granted);
    if (!granted) {
      Alert.alert(
        '通知权限未开启',
        '请在系统设置中手动开启通知权限，以便及时接收消息提醒。',
        [
          { text: '知道了', style: 'cancel' },
        ]
      );
    }
  };

  const settings: NotificationSettingItem[] = [
    {
      key: 'push',
      title: '接收推送通知',
      subtitle: '接收新消息、点赞、评论等推送',
      icon: 'bell-outline',
      value: pushEnabled,
      onValueChange: togglePush,
    },
    {
      key: 'vibration',
      title: '消息震动',
      subtitle: '收到新消息时震动提醒',
      icon: 'vibrate',
      value: vibrationEnabled,
      onValueChange: toggleVibration,
    },
    {
      key: 'sound',
      title: '消息提示音',
      subtitle: '收到新消息时播放提示音',
      icon: 'volume-high',
      value: soundEnabled,
      onValueChange: toggleSound,
    },
  ];

  // 渲染内容
  const renderContent = () => (
    <>
      {/* 消息通知设置 */}
      <View style={styles.section}>
        <View style={styles.sectionHeader}>
          <Text variant="caption" style={styles.sectionTitle}>
            消息通知
          </Text>
        </View>
        {settings.map((item, index) => (
          <View key={item.key}>
            <View style={styles.settingItem}>
              <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.subtitle && (
                  <Text variant="caption" color={colors.text.secondary} style={styles.subtitle}>
                    {item.subtitle}
                  </Text>
                )}
              </View>
              <Switch
                value={item.value}
                onValueChange={item.onValueChange}
                trackColor={{ false: colors.divider, true: colors.primary.main }}
                thumbColor={colors.background.paper}
              />
            </View>
          </View>
        ))}
      </View>

      {/* 系统通知权限状态（仅移动端） */}
      {Platform.OS !== 'web' && systemPushEnabled === false && (
        <TouchableOpacity
          style={[styles.tipContainer, { backgroundColor: colors.error.main + '14' }]}
          onPress={handleRequestSystemPermission}
          activeOpacity={0.7}
        >
          <MaterialCommunityIcons name="alert-circle-outline" size={16} color={colors.error.main} />
          <View style={{ flex: 1 }}>
            <Text variant="caption" color={colors.error.main} style={styles.tipText}>
              系统通知权限未开启，点击前往开启
            </Text>
          </View>
          <MaterialCommunityIcons name="chevron-right" size={16} color={colors.error.main} />
        </TouchableOpacity>
      )}

      {/* 提示信息 */}
      <View style={styles.tipContainer}>
        <MaterialCommunityIcons name="information-outline" size={16} color={colors.text.hint} />
        <Text variant="caption" color={colors.text.hint} style={styles.tipText}>
          关闭推送通知后，您将不再收到任何消息提醒，但消息仍会在应用内显示。
        </Text>
      </View>

      {/* 后台同步模式 */}
      <View style={styles.section}>
        <View style={styles.sectionHeader}>
          <Text variant="caption" style={styles.sectionTitle}>
            后台同步模式
          </Text>
        </View>
        {syncModeOptions.map((option) => (
          <TouchableOpacity
            key={option.mode}
            style={[
              styles.settingItem,
              syncMode === option.mode && styles.settingItemActive,
            ]}
            onPress={() => handleSyncModeChange(option.mode)}
            activeOpacity={0.7}
          >
            <View style={styles.iconContainer}>
              <MaterialCommunityIcons
                name={option.icon as any}
                size={22}
                color={syncMode === option.mode ? colors.primary.main : colors.text.secondary}
              />
            </View>
            <View style={styles.settingContent}>
              <Text
                variant="body"
                color={syncMode === option.mode ? colors.primary.main : colors.text.primary}
              >
                {option.title}
              </Text>
              <Text variant="caption" color={colors.text.secondary} style={styles.subtitle}>
                {option.subtitle}
              </Text>
            </View>
            {syncMode === option.mode && (
              <MaterialCommunityIcons
                name="check"
                size={20}
                color={colors.primary.main}
              />
            )}
          </TouchableOpacity>
        ))}
      </View>

      {/* 实时模式说明 */}
      {syncMode === BackgroundSyncMode.REALTIME && (
        <View style={styles.tipContainer}>
          <MaterialCommunityIcons name="shield-check-outline" size={16} color={colors.text.hint} />
          <Text variant="caption" color={colors.text.hint} style={styles.tipText}>
            实时模式已开启，应用将在通知栏显示常驻通知以保持后台运行。如需更稳定的后台运行，请在系统设置中将本应用加入电池优化白名单。
          </Text>
        </View>
      )}
    </>
  );

  const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });

  return (
    <SafeAreaView style={styles.container} edges={['bottom']}>
      <ScrollView contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding }]}>
        {renderContent()}
      </ScrollView>
    </SafeAreaView>
  );
};

function createNotificationSettingsStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.paper,
    },
    scrollContent: {
      paddingVertical: spacing.lg,
    },
    section: {
      marginBottom: spacing['2xl'],
    },
    sectionHeader: {
      paddingHorizontal: spacing['2xl'],
      marginBottom: spacing.sm,
      marginTop: spacing.sm,
    },
    sectionTitle: {
      fontWeight: '600',
      fontSize: fontSizes.sm,
      color: colors.text.secondary,
      textTransform: 'uppercase',
      letterSpacing: 0.5,
    },
    settingItem: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingVertical: 16,
      paddingHorizontal: spacing['2xl'],
      borderBottomWidth: StyleSheet.hairlineWidth,
      borderBottomColor: colors.divider,
    },
    settingItemActive: {
      backgroundColor: colors.primary.main + '0D',
    },
    iconContainer: {
      width: 24,
      height: 24,
      justifyContent: 'center',
      alignItems: 'center',
      marginRight: spacing.lg,
    },
    settingContent: {
      flex: 1,
    },
    subtitle: {
      marginTop: 2,
    },
    divider: {},
    tipContainer: {
      flexDirection: 'row',
      alignItems: 'flex-start',
      marginHorizontal: spacing['2xl'],
      padding: spacing.md,
      backgroundColor: colors.background.default,
      borderRadius: 14,
      gap: spacing.sm,
    },
    tipText: {
      flex: 1,
      lineHeight: 20,
    },
  });
}

export default NotificationSettingsScreen;
