import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button, TextInput, Alert, ScrollView } from 'react-native';
import MyNativeModule from 'my-native-module';

export default function App() {
  const [token, setToken] = useState('');
  const [conversationName, setConversationName] = useState('');
  const [isInitialized, setIsInitialized] = useState(false);
  const [conversations, setConversations] = useState<any[]>([]);
  const [status, setStatus] = useState('未初始化');

  // 初始化Twilio Conversations客户端
  const initializeClient = async () => {
    if (!token.trim()) {
      Alert.alert('错误', '请输入有效的Twilio令牌');
      return;
    }

    try {
      setStatus('正在初始化...');
      const result = await MyNativeModule.initialize(token);
      console.log('初始化结果:', result);
      setIsInitialized(true);
      setStatus('已初始化');
      Alert.alert('成功', 'Twilio Conversations客户端已初始化');
    } catch (error) {
      console.error('初始化失败:', error);
      setStatus('初始化失败');
      Alert.alert('错误', `初始化失败: ${error}`);
    }
  };

  // 创建新对话
  const createConversation = async () => {
    if (!isInitialized) {
      Alert.alert('错误', '请先初始化Twilio Conversations客户端');
      return;
    }

    if (!conversationName.trim()) {
      Alert.alert('错误', '请输入对话名称');
      return;
    }

    try {
      setStatus('正在创建对话...');
      const conversation = await MyNativeModule.createConversation(conversationName);
      console.log('创建的对话:', conversation);
      Alert.alert('成功', `对话 "${conversation.friendlyName}" 已创建`);
      setConversationName('');
      // 刷新对话列表
      loadConversations();
    } catch (error) {
      console.error('创建对话失败:', error);
      setStatus('创建对话失败');
      Alert.alert('错误', `创建对话失败: ${error}`);
    }
  };

  // 加载对话列表
  const loadConversations = async () => {
    if (!isInitialized) {
      return;
    }

    try {
      setStatus('正在加载对话列表...');
      const conversationList = await MyNativeModule.getConversations();
      console.log('对话列表:', conversationList);
      setConversations(conversationList || []);
      setStatus('已加载对话列表');
    } catch (error) {
      console.error('加载对话列表失败:', error);
      setStatus('加载对话列表失败');
    }
  };

  // 当初始化状态改变时，加载对话列表
  useEffect(() => {
    if (isInitialized) {
      loadConversations();
    }
  }, [isInitialized]);

  return (
    <View style={styles.container}>
      <ScrollView style={styles.scrollView}>
        <Text style={styles.title}>Twilio Conversations Demo</Text>
        
        <Text style={styles.status}>状态: {status}</Text>
        
        <Text style={styles.label}>Twilio访问令牌:</Text>
        <TextInput
          style={styles.input}
          value={token}
          onChangeText={setToken}
          placeholder="输入您的Twilio访问令牌"
          multiline
        />
        
        <Button
          title="初始化客户端"
          onPress={initializeClient}
          disabled={!token.trim() || isInitialized}
        />
        
        <View style={styles.spacer} />
        
        <Text style={styles.label}>对话名称:</Text>
        <TextInput
          style={styles.input}
          value={conversationName}
          onChangeText={setConversationName}
          placeholder="输入新对话的名称"
        />
        
        <Button
          title="创建对话"
          onPress={createConversation}
          disabled={!isInitialized || !conversationName.trim()}
        />
        
        <View style={styles.spacer} />
        
        <Button
          title="刷新对话列表"
          onPress={loadConversations}
          disabled={!isInitialized}
        />
        
        <View style={styles.spacer} />
        
        <Text style={styles.label}>对话列表:</Text>
        {conversations.length > 0 ? (
          conversations.map((conversation, index) => (
            <View style={styles.conversationItem}>
              <Text style={styles.conversationName}>{conversation.friendlyName}</Text>
              <Text style={styles.conversationSid}>SID: {conversation.sid}</Text>
            </View>
          ))
        ) : (
          <Text style={styles.noConversations}>暂无对话</Text>
        )}
      </ScrollView>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    paddingTop: 40,
  },
  scrollView: {
    flex: 1,
    paddingHorizontal: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
  },
  status: {
    fontSize: 16,
    marginBottom: 10,
    textAlign: 'center',
    fontStyle: 'italic',
  },
  label: {
    fontSize: 16,
    marginBottom: 5,
    marginTop: 15,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    marginBottom: 15,
    fontSize: 16,
  },
  spacer: {
    height: 20,
  },
  conversationItem: {
    backgroundColor: '#f5f5f5',
    padding: 15,
    borderRadius: 5,
    marginBottom: 10,
  },
  conversationName: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  conversationSid: {
    fontSize: 14,
    color: '#666',
    marginTop: 5,
  },
  noConversations: {
    textAlign: 'center',
    fontStyle: 'italic',
    color: '#666',
    marginTop: 10,
  },
});
