import * as React from 'react';
import { useEffect, useState } from 'react';
import { 
  View, 
  StyleSheet, 
  NativeModules, 
  Text,
  TouchableOpacity,
  SafeAreaView,
  Alert
} from 'react-native';
import VideoPlayerScreen from './src/views/VideoPlayerScreen';

const { TUTKModule } = NativeModules;

const App = () => {
  const [isInitialized, setIsInitialized] = useState(false);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [currentScreen, setCurrentScreen] = useState('home');

  useEffect(() => {
    initializeTUTK();
    return () => {
      // 组件卸载时清理
      cleanupTUTK();
    };
  }, []);

  const initializeTUTK = async () => {
    try {
      const result = await TUTKModule.initIOTC();
      console.log('TUTK初始化结果:', result);
      setIsInitialized(true);
      // 初始化成功后自动连接设备
      connectToDevice();
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '初始化失败';
      console.error('TUTK初始化错误:', errorMessage);
      setError(errorMessage);
    }
  };

  const cleanupTUTK = async () => {
    try {
      const result = await TUTKModule.deinitIOTC();
      console.log('TUTK清理结果:', result);
      setIsInitialized(false);
      setIsConnected(false);
    } catch (err) {
      console.error('TUTK清理错误:', err);
    }
  };

  const connectToDevice = async () => {
    try {
      const deviceUid = "EXPUAT34KFLWSH6GUHD1";
      const account = "admin";  // 替换为实际账号
      const password = "testpwd"; // 替换为实际密码
      
      const result = await TUTKModule.connectToDevice(deviceUid, account, password);
      console.log('设备连接成功:', result);
      setIsConnected(true);
      Alert.alert('连接成功', `设备连接成功，通道ID: ${result}`);
    } catch (err) {
      console.error('设备连接失败:', err);
      setError(err instanceof Error ? err.message : '连接设备失败');
      Alert.alert('连接失败', err instanceof Error ? err.message : '连接设备失败');
    }
  };

  const renderContent = () => {
    if (error) {
      return (
        <View style={styles.contentContainer}>
          <Text style={styles.errorText}>错误: {error}</Text>
          <TouchableOpacity 
            style={styles.retryButton}
            onPress={initializeTUTK}
          >
            <Text style={styles.retryText}>重试</Text>
          </TouchableOpacity>
        </View>
      );
    }

    switch (currentScreen) {
      case 'video':
        return <VideoPlayerScreen />;
      default:
        return (
          <View style={styles.contentContainer}>
            <Text style={styles.statusText}>
              TUTK状态: {isInitialized ? '已初始化' : '初始化中...'}
            </Text>
            <Text style={styles.statusText}>
              设备连接: {isConnected ? '已连接' : '未连接'}
            </Text>
            {isInitialized && !isConnected && (
              <TouchableOpacity 
                style={styles.connectButton}
                onPress={connectToDevice}
              >
                <Text style={styles.connectText}>连接设备</Text>
              </TouchableOpacity>
            )}
          </View>
        );
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        {renderContent()}
      </View>
      
      <View style={styles.bottomNav}>
        <TouchableOpacity 
          style={[
            styles.navButton,
            currentScreen === 'home' && styles.activeNavButton
          ]}
          onPress={() => setCurrentScreen('home')}
        >
          <Text style={styles.navText}>主页</Text>
        </TouchableOpacity>
        
        <TouchableOpacity 
          style={[
            styles.navButton,
            currentScreen === 'video' && styles.activeNavButton
          ]}
          onPress={() => setCurrentScreen('video')}
        >
          <Text style={styles.navText}>视频</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  content: {
    flex: 1,
  },
  contentContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  statusText: {
    fontSize: 16,
    color: '#333',
    marginBottom: 10,
  },
  errorText: {
    color: 'red',
    textAlign: 'center',
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: '#007AFF',
    padding: 10,
    borderRadius: 5,
  },
  retryText: {
    color: '#fff',
    fontSize: 16,
  },
  connectButton: {
    backgroundColor: '#4CAF50',
    padding: 15,
    borderRadius: 5,
    marginTop: 20,
  },
  connectText: {
    color: '#fff',
    fontSize: 16,
  },
  bottomNav: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderTopColor: '#eee',
    backgroundColor: '#fff',
  },
  navButton: {
    flex: 1,
    padding: 15,
    alignItems: 'center',
  },
  activeNavButton: {
    backgroundColor: '#f0f0f0',
  },
  navText: {
    color: '#333',
    fontSize: 16,
  },
});

export default App;