import React, { useEffect, useState, useCallback, useRef } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { TopNavigation, TopNavigationAction, Icon } from '@ui-kitten/components';
import { useNavigation } from '@react-navigation/native';
import BluetoothManager, { CommandType, ConnectionState } from '../../utils/BluetoothManager';
import { Device } from 'react-native-ble-plx';

const BackIcon = (props) => (
    <Icon {...props} name='arrow-back' />
);

const TestBule = () => {
    const [devices, setDevices] = useState<Device[]>([]);
    const [isScanning, setIsScanning] = useState(false);
    const [isInitialized, setIsInitialized] = useState(false);
    const [connectedDevice, setConnectedDevice] = useState<Device | null>(null);
    const [connectionState, setConnectionState] = useState<ConnectionState>(ConnectionState.DISCONNECTED);
    const [isSending, setIsSending] = useState(false);
    const initAttempted = useRef(false);
    const scanTimeoutRef = useRef<NodeJS.Timeout | null>(null);
    const navigation = useNavigation();

    useEffect(() => {
        if (!initAttempted.current && !isInitialized) {
            initBluetooth();
        }

        // 添加连接状态监听
        const removeConnectionListener = BluetoothManager.addConnectionStateListener((state) => {
            setConnectionState(state);
            if (state === ConnectionState.DISCONNECTED) {
                setConnectedDevice(null);
            }
        });

        return () => {
            if (scanTimeoutRef.current) {
                clearTimeout(scanTimeoutRef.current);
            }
            BluetoothManager.stopScan();
            BluetoothManager.disconnect();
            removeConnectionListener();
            initAttempted.current = false;
        };
    }, []);

    const initBluetooth = useCallback(async () => {
        if (initAttempted.current || isInitialized) {
            return;
        }

        initAttempted.current = true;
        try {
            console.log('开始初始化蓝牙...');
            const initialized = await BluetoothManager.init();
            console.log('蓝牙初始化结果:', initialized);
            
            if (initialized) {
                setIsInitialized(true);
            } else {
                Alert.alert(
                    '提示',
                    '请确保已授予必要权限并开启蓝牙',
                    [
                        { 
                            text: '重试', 
                            onPress: () => {
                                initAttempted.current = false;
                                initBluetooth();
                            }
                        },
                        {
                            text: '取消',
                            style: 'cancel'
                        }
                    ]
                );
            }
        } catch (error) {
            console.error('初始化错误:', error);
            initAttempted.current = false;
            Alert.alert(
                '错误',
                error.message || '蓝牙初始化失败',
                [
                    { 
                        text: '重试', 
                        onPress: () => initBluetooth() 
                    },
                    {
                        text: '取消',
                        style: 'cancel'
                    }
                ]
            );
        }
    }, [isInitialized]);

    const startScan = async () => {
        if (!isInitialized) {
            Alert.alert('提示', '蓝牙未初始化');
            return;
        }

        if (isScanning) {
            return;
        }

        setDevices([]);
        setIsScanning(true);
        
        try {
            await BluetoothManager.startScan((device) => {
                if (device.name && device.name.startsWith('BBLE')) {
                    console.log('发现BBLE设备:', device.name, device.id);
                    setDevices(prev => {
                        if (!prev.find(d => d.id === device.id)) {
                            return [...prev, device];
                        }
                        return prev;
                    });
                }
            });

            scanTimeoutRef.current = setTimeout(() => {
                stopScan();
            }, 5000);
        } catch (error) {
            console.error('扫描失败:', error);
            Alert.alert('错误', '扫描失败');
            setIsScanning(false);
        }
    };

    const stopScan = () => {
        if (scanTimeoutRef.current) {
            clearTimeout(scanTimeoutRef.current);
            scanTimeoutRef.current = null;
        }
        
        if (isInitialized) {
            BluetoothManager.stopScan();
            setIsScanning(false);
        }
    };

    const connectToDevice = async (device: Device) => {
        if (connectionState === ConnectionState.CONNECTING || 
            connectionState === ConnectionState.DISCONNECTING) {
            return;
        }

        try {
            const connected = await BluetoothManager.connectToDevice(device);
            if (connected) {
                setConnectedDevice(device);
            } else {
                Alert.alert('错误', '连接设备失败');
            }
        } catch (error) {
            console.error('连接失败:', error);
            Alert.alert('错误', '连接设备失败');
        }
    };

    const disconnectDevice = async () => {
        try {
            await BluetoothManager.disconnect();
        } catch (error) {
            console.error('断开连接失败:', error);
            Alert.alert('错误', '断开连接失败');
        }
    };

    const sendCommand = async (command: CommandType) => {
        if (connectionState !== ConnectionState.CONNECTED) {
            Alert.alert('提示', '请先连接设备');
            return;
        }

        if (isSending) {
            return;
        }

        setIsSending(true);
        try {
            let success = false;
            switch (command) {
                case CommandType.REBOOT:
                    success = await BluetoothManager.rebootDevice();
                    break;
                case CommandType.OPEN:
                    success = await BluetoothManager.openDevice();
                    break;
                case CommandType.CLOSE:
                    success = await BluetoothManager.closeDevice();
                    break;
                case CommandType.PLAY:
                    success = await BluetoothManager.playResponse();
                    break;
            }

            if (success) {
                console.log('命令发送成功:', command);
            } else {
                Alert.alert('错误', '命令发送失败');
            }
        } catch (error) {
            console.error('发送命令失败:', error);
            Alert.alert('错误', '发送命令失败');
        } finally {
            setIsSending(false);
        }
    };

    const renderDeviceItem = (device: Device) => {
        const isConnected = connectedDevice?.id === device.id;
        return (
            <TouchableOpacity
                key={device.id}
                style={[styles.deviceItem, isConnected && styles.connectedDevice]}
                onPress={() => isConnected ? disconnectDevice() : connectToDevice(device)}
                disabled={connectionState === ConnectionState.CONNECTING || 
                         connectionState === ConnectionState.DISCONNECTING}
            >
                <View>
                    <Text style={styles.deviceName}>{device.name}</Text>
                    <Text style={styles.deviceInfo}>ID: {device.id}</Text>
                    <Text style={styles.deviceInfo}>RSSI: {device.rssi}</Text>
                </View>
                <Text style={[styles.connectionStatus, isConnected && styles.connectedStatus]}>
                    {getConnectionStatusText()}
                </Text>
            </TouchableOpacity>
        );
    };

    const getConnectionStatusText = () => {
        switch (connectionState) {
            case ConnectionState.CONNECTED:
                return '已连接';
            case ConnectionState.CONNECTING:
                return '连接中...';
            case ConnectionState.DISCONNECTING:
                return '断开中...';
            default:
                return '未连接';
        }
    };

    const renderCommandButtons = () => {
        if (connectionState !== ConnectionState.CONNECTED) return null;

        return (
            <View style={styles.commandContainer}>
                <Text style={styles.commandTitle}>设备控制</Text>
                <View style={styles.commandButtonsRow}>
                    <TouchableOpacity 
                        style={[styles.commandButton, isSending && styles.disabledButton]}
                        onPress={() => sendCommand(CommandType.REBOOT)}
                        disabled={isSending}
                    >
                        <Text style={styles.commandButtonText}>重启</Text>
                    </TouchableOpacity>
                    <TouchableOpacity 
                        style={[styles.commandButton, isSending && styles.disabledButton]}
                        onPress={() => sendCommand(CommandType.OPEN)}
                        disabled={isSending}
                    >
                        <Text style={styles.commandButtonText}>打开</Text>
                    </TouchableOpacity>
                </View>
                <View style={styles.commandButtonsRow}>
                    <TouchableOpacity 
                        style={[styles.commandButton, isSending && styles.disabledButton]}
                        onPress={() => sendCommand(CommandType.CLOSE)}
                        disabled={isSending}
                    >
                        <Text style={styles.commandButtonText}>关闭</Text>
                    </TouchableOpacity>
                    <TouchableOpacity 
                        style={[styles.commandButton, isSending && styles.disabledButton]}
                        onPress={() => sendCommand(CommandType.PLAY)}
                        disabled={isSending}
                    >
                        <Text style={styles.commandButtonText}>响应</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    };

    const navigateBack = () => {
        navigation.goBack();
    };

    return (
        <View style={styles.container}>
            <TopNavigation
                title="蓝牙测试"
                alignment="center"
                accessoryLeft={() => (
                    <TopNavigationAction icon={BackIcon} onPress={navigateBack} />
                )}
            />
            
            <View style={styles.statusBar}>
                <Text style={styles.statusText}>
                    状态: {isInitialized ? '已初始化' : '未初始化'}
                </Text>
                <TouchableOpacity 
                    style={[styles.button, isScanning && styles.scanningButton]}
                    onPress={isScanning ? stopScan : startScan}
                    disabled={!isInitialized}
                >
                    <Text style={styles.buttonText}>
                        {isScanning ? '停止搜索' : '开始搜索'}
                    </Text>
                </TouchableOpacity>
            </View>

            <ScrollView style={styles.deviceList}>
                {devices.length === 0 ? (
                    <View style={styles.emptyContainer}>
                        <Text style={styles.emptyText}>
                            {isScanning ? '正在搜索BBLE设备...' : '未发现BBLE设备'}
                        </Text>
                    </View>
                ) : (
                    <>
                        {devices.map(renderDeviceItem)}
                        {renderCommandButtons()}
                    </>
                )}
            </ScrollView>

            {(connectionState === ConnectionState.CONNECTING || 
              connectionState === ConnectionState.DISCONNECTING || 
              isSending) && (
                <View style={styles.loadingContainer}>
                    <View style={styles.loadingContent}>
                        <ActivityIndicator size="large" color="#007AFF" />
                        <Text style={styles.loadingText}>
                            {connectionState === ConnectionState.CONNECTING ? '正在连接设备...' :
                             connectionState === ConnectionState.DISCONNECTING ? '正在断开连接...' :
                             '正在发送命令...'}
                        </Text>
                    </View>
                </View>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
    },
    statusBar: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 16,
        backgroundColor: '#FFF',
        borderBottomWidth: 1,
        borderBottomColor: '#E5E5E5',
    },
    statusText: {
        fontSize: 16,
        color: '#333',
    },
    button: {
        backgroundColor: '#007AFF',
        paddingHorizontal: 16,
        paddingVertical: 8,
        borderRadius: 8,
    },
    scanningButton: {
        backgroundColor: '#FF3B30',
    },
    buttonText: {
        color: '#FFF',
        fontSize: 14,
        fontWeight: '600',
    },
    deviceList: {
        flex: 1,
        padding: 16,
    },
    deviceItem: {
        backgroundColor: '#FFF',
        padding: 16,
        borderRadius: 8,
        marginBottom: 12,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.1,
        shadowRadius: 2,
        elevation: 2,
    },
    connectedDevice: {
        borderColor: '#007AFF',
        borderWidth: 2,
    },
    deviceName: {
        fontSize: 16,
        fontWeight: '600',
        color: '#333',
        marginBottom: 4,
    },
    deviceInfo: {
        fontSize: 14,
        color: '#666',
        marginBottom: 2,
    },
    connectionStatus: {
        fontSize: 14,
        color: '#999',
    },
    connectedStatus: {
        color: '#007AFF',
        fontWeight: '600',
    },
    emptyContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingTop: 100,
    },
    emptyText: {
        fontSize: 16,
        color: '#666',
    },
    loadingContainer: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadingContent: {
        backgroundColor: '#FFF',
        padding: 20,
        borderRadius: 8,
        alignItems: 'center',
    },
    loadingText: {
        marginTop: 12,
        fontSize: 16,
        color: '#333',
    },
    commandContainer: {
        backgroundColor: '#FFF',
        padding: 16,
        borderRadius: 8,
        marginTop: 20,
        marginBottom: 20,
    },
    commandTitle: {
        fontSize: 18,
        fontWeight: '600',
        color: '#333',
        marginBottom: 16,
        textAlign: 'center',
    },
    commandButtonsRow: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginBottom: 12,
    },
    commandButton: {
        backgroundColor: '#007AFF',
        paddingHorizontal: 24,
        paddingVertical: 12,
        borderRadius: 8,
        minWidth: 120,
    },
    commandButtonText: {
        color: '#FFF',
        fontSize: 16,
        fontWeight: '600',
        textAlign: 'center',
    },
    disabledButton: {
        backgroundColor: '#CCCCCC',
    },
});

export default TestBule;