import React, { useCallback, useEffect, useState } from 'react'
import {
  View, Text, FlatList, StyleSheet, TouchableOpacity, SafeAreaView,
  ActivityIndicator,
} from 'react-native'
import { useNavigation, useFocusEffect } from '@react-navigation/native'
import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { ImSDK } from '@xuqm/rn-sdk'
import type { ImGroup } from '@xuqm/rn-sdk'
import type { RootStackParams } from '../../navigation/types'
import { useAuth } from '../../context/AuthContext'

type Nav = NativeStackNavigationProp<RootStackParams>

function parseMemberIds(memberIds: string): string[] {
  try { return JSON.parse(memberIds || '[]') }
  catch { return memberIds ? memberIds.split(',').filter(Boolean) : [] }
}

function GroupRow({ group, onPress }: { group: ImGroup; onPress(): void }) {
  const letter = (group.name || 'G').charAt(0).toUpperCase()
  return (
    <TouchableOpacity style={styles.row} onPress={onPress} activeOpacity={0.7}>
      <View style={styles.avatar}><Text style={styles.avatarText}>{letter}</Text></View>
      <View style={styles.body}>
        <Text style={styles.name}>{group.name}</Text>
        <Text style={styles.memberCount}>{parseMemberIds(group.memberIds).length} 人</Text>
      </View>
      <Text style={styles.arrow}>›</Text>
    </TouchableOpacity>
  )
}

export default function GroupListScreen() {
  const navigation = useNavigation<Nav>()
  const [groups, setGroups] = useState<ImGroup[]>([])
  const [loading, setLoading] = useState(true)

  const fetchGroups = async () => {
    setLoading(true)
    try {
      const list = await ImSDK.listGroups()
      setGroups(list)
    } catch {
      /* silently fail */
    } finally {
      setLoading(false)
    }
  }

  useFocusEffect(useCallback(() => { fetchGroups() }, []))

  return (
    <SafeAreaView style={styles.root}>
      <View style={styles.header}>
        <Text style={styles.title}>群聊</Text>
        <TouchableOpacity style={styles.createBtn} onPress={() => navigation.navigate('CreateGroup')}>
          <Text style={styles.createBtnText}>+ 创建</Text>
        </TouchableOpacity>
      </View>
      {loading
        ? <ActivityIndicator style={{ flex: 1 }} color="#07C160" />
        : (
          <FlatList
            data={groups}
            keyExtractor={g => g.id}
            renderItem={({ item }) => (
              <GroupRow
                group={item}
                onPress={() => navigation.navigate('GroupChat', { groupId: item.id, groupName: item.name })}
              />
            )}
            ItemSeparatorComponent={() => <View style={styles.sep} />}
            ListEmptyComponent={<View style={styles.empty}><Text style={styles.emptyText}>还没有群聊</Text></View>}
          />
        )
      }
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: '#f5f5f5' },
  header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16, backgroundColor: '#fff', borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#e0e0e0' },
  title: { fontSize: 18, fontWeight: '700', color: '#111' },
  createBtn: { paddingHorizontal: 12, paddingVertical: 6, backgroundColor: '#07C160', borderRadius: 6 },
  createBtnText: { color: '#fff', fontSize: 13, fontWeight: '600' },
  row: { flexDirection: 'row', alignItems: 'center', padding: 12, backgroundColor: '#fff' },
  avatar: { width: 46, height: 46, borderRadius: 8, backgroundColor: '#5856d6', alignItems: 'center', justifyContent: 'center', marginRight: 12 },
  avatarText: { color: '#fff', fontSize: 18, fontWeight: '600' },
  body: { flex: 1 },
  name: { fontSize: 16, fontWeight: '500', color: '#111' },
  memberCount: { fontSize: 13, color: '#888', marginTop: 2 },
  arrow: { color: '#ccc', fontSize: 20 },
  sep: { height: StyleSheet.hairlineWidth, backgroundColor: '#e0e0e0', marginLeft: 70 },
  empty: { alignItems: 'center', paddingTop: 80 },
  emptyText: { color: '#bbb', fontSize: 15 },
})
