/**
 * CreateGroupScreen 创建群聊界面（现代化扁平风格）
 * 允许用户创建新的群聊，设置群名称、描述，并选择初始成员
 * 支持响应式布局
 * 
 * 设计风格：
 * - 纯白/浅色背景，扁平化设计
 * - 灰色填充输入框，圆角14px
 * - 橙色圆角按钮
 * - 清晰的标签 + 输入框分组
 */

import React, { useState, useMemo, useEffect, useRef } from 'react';
import {
  View,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  TextInput,
  FlatList,
  Image,
  Platform,
  Animated,
  KeyboardAvoidingView,
  ActivityIndicator,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { blurActiveElement } from '../../infrastructure/platform';
import * as ImagePicker from 'expo-image-picker';
import { spacing, fontSizes, borderRadius, shadows, useAppColors, type AppColors } from '../../theme';
import { groupService } from '@/services/message';
import { uploadService } from '@/services/upload';
import { Avatar, Text, Loading } from '../../components/common';
import { User } from '../../types';
import MutualFollowSelectorModal from './components/MutualFollowSelectorModal';

const CreateGroupScreen: React.FC = () => {
  const colors = useAppColors();
  const styles = useMemo(() => createCreateGroupStyles(colors), [colors]);
  const router = useRouter();

  // 表单状态
  const [groupName, setGroupName] = useState('');
  const [groupDescription, setGroupDescription] = useState('');
  const [groupAvatar, setGroupAvatar] = useState<string | null>(null);
  const [selectedMembers, setSelectedMembers] = useState<User[]>([]);
  const [selectedMemberIds, setSelectedMemberIds] = useState<Set<string>>(new Set());

  // 提交状态
  const [submitting, setSubmitting] = useState(false);
  const [uploadingAvatar, setUploadingAvatar] = useState(false);

  // 邀请成员模态框状态
  const [inviteModalVisible, setInviteModalVisible] = useState(false);

  // 动画值
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(20)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 400,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);

  useEffect(() => {
    if (inviteModalVisible) {
      blurActiveElement();
    }
  }, [inviteModalVisible]);

  // 移除已选成员
  const removeSelectedMember = (userId: string) => {
    const newSelectedIds = new Set(selectedMemberIds);
    newSelectedIds.delete(userId);
    setSelectedMemberIds(newSelectedIds);
    setSelectedMembers(prev => prev.filter(m => m.id !== userId));
  };

  // 选择群头像
  const handleSelectAvatar = async () => {
    try {
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        Alert.alert('提示', '需要访问相册权限才能选择头像');
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: 'images',
        allowsEditing: true,
        aspect: [1, 1],
        quality: 0.8,
      });

      if (!result.canceled && result.assets && result.assets.length > 0) {
        const selectedAsset = result.assets[0];
        setUploadingAvatar(true);

        try {
          const uploadResult = await uploadService.uploadGroupAvatar({
            uri: selectedAsset.uri,
            type: selectedAsset.mimeType || 'image/jpeg',
          });

          if (uploadResult && uploadResult.url) {
            setGroupAvatar(uploadResult.url);
          } else {
            Alert.alert('上传失败', '头像上传失败，请重试');
          }
        } catch (error) {
          console.error('上传头像失败:', error);
          Alert.alert('上传失败', '头像上传失败，请重试');
        } finally {
          setUploadingAvatar(false);
        }
      }
    } catch (error) {
      console.error('选择头像失败:', error);
      Alert.alert('错误', '选择头像时发生错误');
    }
  };

  // 创建群组
  const handleCreateGroup = async () => {
    // 验证群名称
    if (!groupName.trim()) {
      Alert.alert('提示', '请输入群名称');
      return;
    }

    if (groupName.length > 50) {
      Alert.alert('提示', '群名称最多50个字符');
      return;
    }

    if (groupDescription.length > 500) {
      Alert.alert('提示', '群描述最多500个字符');
      return;
    }

    setSubmitting(true);
    try {
      const memberIds = selectedMembers.map(m => m.id);
      const response = await groupService.createGroup({
        name: groupName.trim(),
        description: groupDescription.trim() || undefined,
        member_ids: memberIds.length > 0 ? memberIds : undefined,
      });

      // 如果设置了头像，更新群头像
      if (groupAvatar && response.id) {
        try {
          await groupService.setGroupAvatar(response.id, groupAvatar);
        } catch (avatarError) {
          console.error('设置群头像失败:', avatarError);
        }
      }

      Alert.alert('成功', '群组创建成功', [
        {
          text: '确定',
          onPress: () => router.back(),
        },
      ]);
    } catch (error: any) {
      console.error('创建群组失败:', error);
      Alert.alert('创建失败', error.message || '创建群组时发生错误，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  // 渲染已选成员
  const renderSelectedMember = ({ item }: { item: User }) => (
    <View style={styles.selectedMemberItem}>
      <Avatar source={item.avatar} size={48} name={item.nickname} />
      <TouchableOpacity
        style={styles.removeMemberButton}
        onPress={() => removeSelectedMember(item.id)}
      >
        <View style={styles.removeIconContainer}>
          <MaterialCommunityIcons name="close" size={12} color={colors.background.paper} />
        </View>
      </TouchableOpacity>
      <Text variant="caption" numberOfLines={1} style={styles.selectedMemberName}>
        {item.nickname}
      </Text>
    </View>
  );

  const handleConfirmMembers = (users: User[]) => {
    setSelectedMembers(users);
    setSelectedMemberIds(new Set(users.map(user => user.id)));
    setInviteModalVisible(false);
  };

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardView}
      >
        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}
        >
          <Animated.View
            style={[
              styles.content,
              {
                opacity: fadeAnim,
                transform: [{ translateY: slideAnim }],
              },
            ]}
          >
            {/* 标题区域 */}
            <View style={styles.titleSection}>
              <Text style={styles.title}>创建群聊</Text>
              <View style={styles.underline} />
              <Text style={styles.subtitle}>填写群信息并邀请成员</Text>
            </View>

            {/* 群头像区域 */}
            <View style={styles.avatarSection}>
              <TouchableOpacity style={styles.avatarWrapper} onPress={handleSelectAvatar} disabled={uploadingAvatar}>
                {uploadingAvatar ? (
                  <View style={styles.avatarPlaceholder}>
                    <Loading />
                  </View>
                ) : groupAvatar ? (
                  <Image source={{ uri: groupAvatar }} style={styles.avatarImage} />
                ) : (
                  <View style={styles.avatarPlaceholder}>
                    <MaterialCommunityIcons name="camera" size={28} color={colors.text.hint} />
                  </View>
                )}
                <View style={styles.avatarBadge}>
                  <MaterialCommunityIcons name="pencil" size={12} color={colors.background.paper} />
                </View>
              </TouchableOpacity>
              <Text style={styles.avatarHint}>点击设置群头像</Text>
            </View>

            {/* 群名称输入 */}
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>群名称 <Text style={styles.requiredMark}>*</Text></Text>
              <View style={styles.inputWrapper}>
                <TextInput
                  style={styles.input}
                  value={groupName}
                  onChangeText={setGroupName}
                  placeholder="请输入群名称"
                  placeholderTextColor={colors.text.hint}
                  maxLength={50}
                  cursorColor={colors.primary.main}
                  selectionColor={`${colors.primary.main}40`}
                  autoCapitalize="none"
                />
                {groupName.length > 0 && (
                  <MaterialCommunityIcons name="check-circle" size={20} color={colors.primary.main} style={styles.checkIcon} />
                )}
              </View>
              <Text style={styles.charCount}>{groupName.length}/50</Text>
            </View>

            {/* 群描述输入 */}
            <View style={styles.inputContainer}>
              <Text style={styles.inputLabel}>群描述</Text>
              <View style={[styles.inputWrapper, styles.textAreaWrapper]}>
                <TextInput
                  style={[styles.input, styles.textArea]}
                  value={groupDescription}
                  onChangeText={setGroupDescription}
                  placeholder="介绍一下这个群聊吧..."
                  placeholderTextColor={colors.text.hint}
                  maxLength={500}
                  multiline
                  numberOfLines={4}
                  textAlignVertical="top"
                  cursorColor={colors.primary.main}
                  selectionColor={`${colors.primary.main}40`}
                />
              </View>
              <Text style={styles.charCount}>{groupDescription.length}/500</Text>
            </View>

            {/* 已选成员 */}
            {selectedMembers.length > 0 && (
              <View style={styles.membersSection}>
                <View style={styles.sectionHeader}>
                  <Text style={styles.sectionTitle}>已选成员</Text>
                  <Text style={styles.memberCount}>{selectedMembers.length}人</Text>
                </View>
                <FlatList
                  data={selectedMembers}
                  renderItem={renderSelectedMember}
                  keyExtractor={item => item.id}
                  horizontal
                  showsHorizontalScrollIndicator={false}
                  contentContainerStyle={styles.selectedMembersList}
                />
              </View>
            )}

            {/* 邀请成员按钮 */}
            <TouchableOpacity
              style={styles.inviteButton}
              onPress={() => setInviteModalVisible(true)}
              activeOpacity={0.8}
            >
              <View style={styles.inviteIconContainer}>
                <MaterialCommunityIcons name="account-plus" size={22} color={colors.primary.main} />
              </View>
              <View style={styles.inviteTextContainer}>
                <Text style={styles.inviteTitle}>邀请成员</Text>
                <Text style={styles.inviteSubtitle}>仅可从互关好友中选择成员加入群聊</Text>
              </View>
              <MaterialCommunityIcons name="chevron-right" size={22} color={colors.text.hint} />
            </TouchableOpacity>

            {/* 创建按钮 */}
            <TouchableOpacity
              style={[
                styles.createButton,
                (!groupName.trim() || submitting) && styles.createButtonDisabled,
              ]}
              onPress={handleCreateGroup}
              disabled={!groupName.trim() || submitting}
              activeOpacity={0.9}
            >
              {submitting ? (
                <ActivityIndicator size="small" color={colors.text.inverse} />
              ) : (
                <Text style={styles.createButtonText}>创建群聊</Text>
              )}
            </TouchableOpacity>
          </Animated.View>
        </ScrollView>
      </KeyboardAvoidingView>

      <MutualFollowSelectorModal
        visible={inviteModalVisible}
        title="邀请成员"
        confirmText="完成"
        initialSelectedIds={Array.from(selectedMemberIds)}
        onClose={() => setInviteModalVisible(false)}
        onConfirm={handleConfirmMembers}
      />
    </SafeAreaView>
  );
};

function createCreateGroupStyles(colors: AppColors) {
  return StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background.paper,
    },
    keyboardView: {
      flex: 1,
    },
    scrollView: {
      flex: 1,
    },
    scrollContent: {
      flexGrow: 1,
      paddingHorizontal: 28,
      paddingTop: 40,
      paddingBottom: 40,
    },
    content: {
      flex: 1,
      maxWidth: 400,
      width: '100%',
      alignSelf: 'center',
    },

    // 标题区域
    titleSection: {
      marginBottom: 32,
      marginTop: 12,
    },
    title: {
      fontSize: 28,
      fontWeight: '700',
      color: colors.text.primary,
      lineHeight: 36,
    },
    underline: {
      width: 40,
      height: 4,
      backgroundColor: colors.primary.main,
      borderRadius: 2,
      marginTop: 12,
      marginBottom: 12,
    },
    subtitle: {
      fontSize: 15,
      color: colors.text.secondary,
    },

    // 头像区域
    avatarSection: {
      alignItems: 'center',
      marginBottom: 32,
    },
    avatarWrapper: {
      position: 'relative',
    },
    avatarImage: {
      width: 88,
      height: 88,
      borderRadius: 44,
      borderWidth: 3,
      borderColor: colors.primary.light + '40',
    },
    avatarPlaceholder: {
      width: 88,
      height: 88,
      borderRadius: 44,
      backgroundColor: colors.background.default,
      justifyContent: 'center',
      alignItems: 'center',
      borderWidth: 2,
      borderColor: colors.divider,
      borderStyle: 'dashed',
    },
    avatarBadge: {
      position: 'absolute',
      bottom: 0,
      right: 0,
      backgroundColor: colors.primary.main,
      width: 28,
      height: 28,
      borderRadius: 14,
      justifyContent: 'center',
      alignItems: 'center',
      borderWidth: 3,
      borderColor: colors.background.paper,
    },
    avatarHint: {
      marginTop: 10,
      fontSize: 13,
      color: colors.text.hint,
      fontWeight: '500',
    },

    // 输入框区域（参考登录注册风格）
    inputContainer: {
      marginBottom: 24,
    },
    inputLabel: {
      fontSize: 14,
      fontWeight: '500',
      color: colors.text.secondary,
      marginBottom: 10,
    },
    requiredMark: {
      color: colors.error.main,
      fontWeight: '600',
    },
    inputWrapper: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.background.default,
      borderRadius: 14,
      paddingHorizontal: 18,
      minHeight: 56,
      borderWidth: 1,
      borderColor: 'transparent',
    },
    input: {
      flex: 1,
      fontSize: 16,
      color: colors.text.primary,
      minHeight: 56,
    },
    textAreaWrapper: {
      paddingVertical: 14,
      alignItems: 'flex-start',
    },
    textArea: {
      minHeight: 100,
      lineHeight: 22,
      textAlignVertical: 'top',
    },
    checkIcon: {
      marginLeft: 8,
    },
    charCount: {
      textAlign: 'right',
      marginTop: 6,
      fontSize: 12,
      color: colors.text.hint,
      fontWeight: '500',
    },

    // 成员区域
    membersSection: {
      marginBottom: 24,
    },
    sectionHeader: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 12,
    },
    sectionTitle: {
      fontSize: 14,
      fontWeight: '500',
      color: colors.text.secondary,
    },
    memberCount: {
      fontSize: 13,
      color: colors.primary.main,
      fontWeight: '600',
    },
    selectedMembersList: {
      paddingVertical: 4,
    },
    selectedMemberItem: {
      alignItems: 'center',
      marginRight: 16,
      width: 64,
    },
    removeMemberButton: {
      position: 'absolute',
      top: -4,
      right: 4,
    },
    removeIconContainer: {
      backgroundColor: colors.text.secondary,
      borderRadius: 10,
      width: 20,
      height: 20,
      justifyContent: 'center',
      alignItems: 'center',
      borderWidth: 2,
      borderColor: colors.background.paper,
    },
    selectedMemberName: {
      marginTop: 4,
      textAlign: 'center',
      width: '100%',
      fontWeight: '600',
      fontSize: 12,
      color: colors.text.primary,
    },

    // 邀请按钮
    inviteButton: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.background.default,
      borderRadius: 14,
      padding: 16,
      marginBottom: 32,
    },
    inviteIconContainer: {
      width: 44,
      height: 44,
      borderRadius: 12,
      backgroundColor: colors.primary.light + '15',
      justifyContent: 'center',
      alignItems: 'center',
      marginRight: 14,
    },
    inviteTextContainer: {
      flex: 1,
    },
    inviteTitle: {
      fontWeight: '600',
      fontSize: 16,
      color: colors.text.primary,
      marginBottom: 2,
    },
    inviteSubtitle: {
      fontSize: 13,
      color: colors.text.secondary,
    },

    // 创建按钮
    createButton: {
      height: 56,
      borderRadius: 14,
      backgroundColor: colors.primary.main,
      alignItems: 'center',
      justifyContent: 'center',
      marginBottom: 16,
    },
    createButtonDisabled: {
      opacity: 0.6,
    },
    createButtonText: {
      fontSize: 17,
      fontWeight: '600',
      color: colors.text.inverse,
    },
  });
}

export default CreateGroupScreen;
