import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { authService } from '../../services';
import { spacing, borderRadius, fontSizes, useAppColors, type AppColors } from '../../theme';
import { Text } from '../../components/common';
import { useResponsive, useResponsiveSpacing } from '../../hooks';
import type { PrivacySettingsDTO, VisibilityLevel } from '../../types/dto';

const CONTENT_MAX_WIDTH = 720;

const VISIBILITY_OPTIONS: { value: VisibilityLevel; label: string; description: string }[] = [
  { value: 'everyone', label: '所有人可见', description: '任何人都可查看' },
  { value: 'following', label: '仅关注的人可见', description: '只有你关注的人可查看' },
  { value: 'self', label: '仅自己可见', description: '只有自己可查看' },
];

const PRIVACY_ITEMS: { key: keyof PrivacySettingsDTO; title: string; description: string }[] = [
  { key: 'followers_visibility', title: '粉丝列表', description: '谁可以查看你的粉丝列表' },
  { key: 'following_visibility', title: '关注列表', description: '谁可以查看你的关注列表' },
  { key: 'posts_visibility', title: '帖子列表', description: '谁可以查看你的帖子列表' },
  { key: 'favorites_visibility', title: '收藏列表', description: '谁可以查看你的收藏列表' },
];

function createPrivacySettingsStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.paper,
    },
    loadingWrap: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
    },
    scrollContent: {
      paddingVertical: spacing.lg,
    },
    content: {
      maxWidth: CONTENT_MAX_WIDTH,
      alignSelf: 'center',
      width: '100%',
    },
    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,
    },
    // 隐私设置项 - 扁平化卡片风格
    item: {
      backgroundColor: colors.background.default,
      borderRadius: 14,
      padding: spacing.lg,
      marginHorizontal: spacing['2xl'],
      marginBottom: spacing.md,
    },
    itemHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      marginBottom: spacing.sm,
    },
    itemTitle: {
      fontWeight: '600',
      fontSize: fontSizes.md,
      color: colors.text.primary,
    },
    itemDescription: {
      fontSize: fontSizes.sm,
      color: colors.text.secondary,
      marginBottom: spacing.md,
    },
    optionsRow: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: spacing.sm,
    },
    // 选项按钮 - 扁平化风格
    optionButton: {
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.sm,
      borderRadius: borderRadius.full,
      borderWidth: 1,
      borderColor: colors.divider,
      backgroundColor: colors.background.paper,
    },
    optionButtonActive: {
      backgroundColor: colors.primary.main,
      borderColor: colors.primary.main,
    },
    optionText: {
      fontSize: 13,
      color: colors.text.primary,
    },
    optionTextActive: {
      color: colors.text.inverse,
      fontWeight: '500',
    },
  });
}

export const PrivacySettingsScreen: React.FC = () => {
  const colors = useAppColors();
  const styles = useMemo(() => createPrivacySettingsStyles(colors), [colors]);
  const router = useRouter();
  const { isMobile } = useResponsive();
  const insets = useSafeAreaInsets();
  const [settings, setSettings] = useState<PrivacySettingsDTO | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const responsivePadding = useResponsiveSpacing({ xs: 8, sm: 12, md: 16, lg: 24, xl: 32 });

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

  const loadSettings = useCallback(async () => {
    try {
      const result = await authService.getPrivacySettings();
      if (result) {
        setSettings(result);
      }
    } catch (error) {
      console.error('加载隐私设置失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadSettings();
  }, [loadSettings]);

  const updateSetting = useCallback(async (key: keyof PrivacySettingsDTO, value: VisibilityLevel) => {
    if (!settings) return;
    
    const newSettings = { ...settings, [key]: value };
    setSettings(newSettings);
    
    setSaving(true);
    try {
      const ok = await authService.updatePrivacySettings({
        [key]: value,
      });
      if (!ok) {
        Alert.alert('失败', '保存设置失败，请稍后重试');
        setSettings(settings);
      }
    } catch (error) {
      console.error('保存隐私设置失败:', error);
      setSettings(settings);
    } finally {
      setSaving(false);
    }
  }, [settings]);

  if (loading) {
    return (
      <SafeAreaView style={styles.container} edges={['bottom']}>
        <View style={styles.loadingWrap}>
          <ActivityIndicator size="large" color={colors.primary.main} />
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['bottom']}>
      <ScrollView contentContainerStyle={[styles.scrollContent, { paddingBottom: scrollBottomInset, paddingHorizontal: responsivePadding }]}>
        <View style={styles.content}>
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <Text variant="caption" style={styles.sectionTitle}>
                隐私设置
              </Text>
            </View>
            
            {PRIVACY_ITEMS.map((item) => (
              <View key={item.key} style={styles.item}>
                <Text variant="body" style={styles.itemTitle}>
                  {item.title}
                </Text>
                <Text variant="caption" color={colors.text.secondary} style={styles.itemDescription}>
                  {item.description}
                </Text>
                <View style={styles.optionsRow}>
                  {VISIBILITY_OPTIONS.map((option) => {
                    const isActive = settings?.[item.key] === option.value;
                    return (
                      <TouchableOpacity
                        key={option.value}
                        style={[styles.optionButton, isActive && styles.optionButtonActive]}
                        onPress={() => updateSetting(item.key, option.value)}
                        activeOpacity={0.7}
                      >
                        <Text
                          variant="caption"
                          style={[styles.optionText, isActive ? styles.optionTextActive : {}]}
                        >
                          {option.label}
                        </Text>
                      </TouchableOpacity>
                    );
                  })}
                </View>
              </View>
            ))}
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default PrivacySettingsScreen;
