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 }[] = [
  { value: 'everyone', label: '所有人可见' },
  { value: 'following', label: '仅关注的人可见' },
  { value: 'self', label: '仅自己可见' },
];

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: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      paddingVertical: spacing.lg,
      marginHorizontal: spacing['2xl'],
      borderBottomWidth: StyleSheet.hairlineWidth,
      borderBottomColor: colors.divider,
    },
    itemLast: {
      borderBottomWidth: 0,
    },
    itemTextWrap: {
      flex: 1,
      marginRight: spacing.md,
    },
    itemTitle: {
      fontWeight: '600',
      fontSize: fontSizes.md,
      color: colors.text.primary,
      marginBottom: spacing.xs,
    },
    itemDescription: {
      fontSize: fontSizes.sm,
      color: colors.text.secondary,
    },
    // 无背景色的选择框，紧贴右侧
    selectBox: {
      flexDirection: 'row',
      alignItems: 'center',
      paddingVertical: spacing.xs,
    },
    selectBoxText: {
      fontSize: fontSizes.sm,
      color: colors.text.secondary,
      marginRight: spacing.xs,
    },
    // 原位展开的下拉菜单
    dropdownMenu: {
      position: 'absolute',
      right: 0,
      top: '100%',
      marginTop: 4,
      backgroundColor: colors.background.paper,
      borderRadius: borderRadius.md,
      borderWidth: StyleSheet.hairlineWidth,
      borderColor: colors.divider,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.1,
      shadowRadius: 4,
      elevation: 4,
      zIndex: 100,
      minWidth: 160,
    },
    dropdownOption: {
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.sm,
      borderBottomWidth: StyleSheet.hairlineWidth,
      borderBottomColor: colors.divider,
    },
    dropdownOptionLast: {
      borderBottomWidth: 0,
    },
    dropdownOptionText: {
      fontSize: fontSizes.sm,
      color: colors.text.primary,
    },
    dropdownOptionTextActive: {
      color: colors.primary.main,
      fontWeight: '600',
    },
  });
}

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 [openPicker, setOpenPicker] = useState<keyof PrivacySettingsDTO | null>(null);
  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]);

  const getLabel = (value?: VisibilityLevel) =>
    VISIBILITY_OPTIONS.find((o) => o.value === value)?.label ?? '请选择';

  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}>
            {PRIVACY_ITEMS.map((item, index) => {
              const isOpen = openPicker === item.key;
              return (
                <View
                  key={item.key}
                  style={[
                    styles.item,
                    index === PRIVACY_ITEMS.length - 1 && styles.itemLast,
                  ]}
                >
                  <View style={styles.itemTextWrap}>
                    <Text variant="body" style={styles.itemTitle}>
                      {item.title}
                    </Text>
                    <Text variant="caption" color={colors.text.secondary} style={styles.itemDescription}>
                      {item.description}
                    </Text>
                  </View>

                  <TouchableOpacity
                    style={styles.selectBox}
                    onPress={() => setOpenPicker(isOpen ? null : item.key)}
                    activeOpacity={0.7}
                  >
                    <Text style={styles.selectBoxText}>
                      {getLabel(settings?.[item.key])}
                    </Text>
                    <MaterialCommunityIcons
                      name={isOpen ? 'chevron-up' : 'chevron-down'}
                      size={18}
                      color={colors.text.secondary}
                    />
                  </TouchableOpacity>

                  {/* 原位展开的下拉选项 */}
                  {isOpen && (
                    <View style={styles.dropdownMenu}>
                      {VISIBILITY_OPTIONS.map((option, optIndex) => {
                        const isActive = settings?.[item.key] === option.value;
                        return (
                          <TouchableOpacity
                            key={option.value}
                            style={[
                              styles.dropdownOption,
                              optIndex === VISIBILITY_OPTIONS.length - 1 && styles.dropdownOptionLast,
                            ]}
                            onPress={() => {
                              updateSetting(item.key, option.value);
                              setOpenPicker(null);
                            }}
                            activeOpacity={0.7}
                          >
                            <Text
                              variant="body"
                              style={[
                                styles.dropdownOptionText,
                                isActive ? styles.dropdownOptionTextActive : undefined,
                              ]}
                            >
                              {option.label}
                            </Text>
                          </TouchableOpacity>
                        );
                      })}
                    </View>
                  )}
                </View>
              );
            })}
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default PrivacySettingsScreen;
