import React, { useState, useEffect, useRef } from 'react';
import { View, Image, Text, StyleSheet, TouchableOpacity, Alert, Animated } from 'react-native';
import { Spinner } from '@ui-kitten/components';
import { apiService } from '../utils/api';
import BluetoothManager, { CommandType, ConnectionState } from '../utils/BluetoothManager';
import { rpx } from '../utils/rpx';
import Slider from './slider';

interface DeviceControlProps {
    defaultDevice: any;
    onDeviceUpdate?: () => void;
}

const DeviceControl: React.FC<DeviceControlProps> = ({ defaultDevice, onDeviceUpdate }) => {
    const [isConnecting, setIsConnecting] = useState(false);
    const [showBluetoothStatus, setShowBluetoothStatus] = useState(false);
    const [connectionState, setConnectionState] = useState<ConnectionState>(ConnectionState.DISCONNECTED);
    const retryAttemptRef = useRef(false);
    const fadeAnim = useRef(new Animated.Value(0)).current;
    const slideAnim = useRef(new Animated.Value(-rpx(272))).current;

    const showWithAnimation = () => {
        setShowBluetoothStatus(true);
        Animated.parallel([
            Animated.timing(fadeAnim, {
                toValue: 1,
                duration: 300,
                useNativeDriver: true,
            }),
            Animated.spring(slideAnim, {
                toValue: 0,
                useNativeDriver: true,
                friction: 8,
            })
        ]).start();
    };

    const hideWithAnimation = () => {
        Animated.parallel([
            Animated.timing(fadeAnim, {
                toValue: 0,
                duration: 300,
                useNativeDriver: true,
            }),
            Animated.timing(slideAnim, {
                toValue: -rpx(272),
                duration: 300,
                useNativeDriver: true,
            })
        ]).start(() => {
            setShowBluetoothStatus(false);
        });
    };

    const handleBluetoothConnection = async (isRetry = false): Promise<boolean> => {
        if (isConnecting) return false;

        try {
            setIsConnecting(true);
            showWithAnimation();
            const targetMac = defaultDevice?.mac// 暂时使用固定MAC
            console.log(`${isRetry ? '重试' : '开始'}连接设备, 目标MAC:`, targetMac);

            const initialized = await BluetoothManager.init();
            if (!initialized) {
                throw new Error('蓝牙初始化失败');
            }

            let targetDevice = null;
            let scannedDevices = new Set();

            await BluetoothManager.startScan((device) => {
                const deviceName = device.name || device.localName || '';
                const macMatch = deviceName.match(/BBLE:([A-Fa-f0-9]{12})/);
                const deviceMac = macMatch ? macMatch[1] : '';

                if (!scannedDevices.has(deviceMac) && deviceMac) {
                    scannedDevices.add(deviceMac);
                    console.log('扫描到设备:', {
                        name: deviceName,
                        extractedMac: deviceMac,
                        rssi: device.rssi
                    });
                }

                if (deviceMac === targetMac) {
                    console.log('找到目标设备:', deviceMac);
                    targetDevice = device;
                    BluetoothManager.stopScan();
                }
            });

            await new Promise(resolve => setTimeout(resolve, 5000));
            BluetoothManager.stopScan();

            if (!targetDevice) {
                throw new Error('未找到指定设备，请确保设备在范围内且已开启');
            }

            const connected = await BluetoothManager.connectToDevice(targetDevice);
            if (!connected) {
                throw new Error('连接设备失败');
            }

            console.log('成功连接到设备');
            retryAttemptRef.current = false;
            return true;

        } catch (error) {
            console.error(`${isRetry ? '重试' : ''}蓝牙连接失败:`, error);
            if (!isRetry && !retryAttemptRef.current) {
                console.log('将在3秒后尝试重新连接...');
                retryAttemptRef.current = true;
                setTimeout(async () => {
                    await handleBluetoothConnection(true);
                }, 3000);
            } else {
                setTimeout(hideWithAnimation, 3000);
            }
            return false;
        } finally {
            setIsConnecting(false);
        }
    };

    const handleRing = async () => {
        console.log('响铃操作 - 设备信息:', {
            完整设备信息: defaultDevice,
            设备SN: defaultDevice?.sn,
            当前时间: new Date().toISOString()
        });

        if (!defaultDevice?.sn) {
            Alert.alert('提示', '请先选择设备');
            return;
        }

        try {
            const response = await apiService.ring(defaultDevice.sn);
            console.log('响铃API响应:', response);

            if (response.code != 200) {
                retryAttemptRef.current = false;
                const connected = await handleBluetoothConnection(false);
                if (connected) {
                    await BluetoothManager.playResponse();
                }
            }
        } catch (error) {
            console.error('响铃失败:', error);
            retryAttemptRef.current = false;
            const connected = await handleBluetoothConnection(false);
            if (connected) {
                await BluetoothManager.playResponse();
            }
        }
    };

    const handleLockStatus = async (status: boolean) => {
        if (!defaultDevice || !defaultDevice.sn) {
            console.warn('设备数据无效:', {
                设备对象: defaultDevice,
                操作类型: status ? '开锁' : '关锁'
            });
            Alert.alert('提示', '设备数据无效，请确保设备已正确选择');
            return;
        }

        const response = await (status ?
            apiService.unlocking(defaultDevice.sn) :
            apiService.lock(defaultDevice.sn));

        console.log('开关锁API响应:', {
            响应数据: response,
            操作类型: status ? '开锁' : '关锁',
            时间: new Date().toISOString()
        });

        if (response.code != 200) {
            retryAttemptRef.current = false;
            const connected = await handleBluetoothConnection(false);

            if (connected) {
                try {
                    await (status ?
                        BluetoothManager.openDevice() :
                        BluetoothManager.closeDevice());

                    if (onDeviceUpdate) {
                        onDeviceUpdate();  // 蓝牙操作成功后调用更新
                    }
                } catch (bluetoothError) {
                    console.error('蓝牙命令执行失败:', bluetoothError);
                    Alert.alert('错误', '蓝牙命令执行失败，请重试');
                }
            } else {
                Alert.alert('提示', '蓝牙连接失败，请确保设备在范围内且已开启');
            }
        } else {
            // API 调用成功，直接更新状态
            if (onDeviceUpdate) {
                onDeviceUpdate();
            }
        }
    };

    const getPowerColor = (power: number): string => {
        if (power >= 60) {
            return 'rgba(89, 202, 112, 0.5)';
        } else if (power >= 20) {
            return 'rgba(255, 149, 0, 0.5)';
        } else {
            return 'rgba(255, 69, 58, 0.5)';
        }
    };
    const calculateTimeRemaining = (expirationTime: string): string => {
        const expiration = new Date(expirationTime).getTime();
        const now = new Date().getTime();
        const diff = expiration - now;

        if (diff <= 0) return '已过期';

        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

        return `${days}天${hours}小时${minutes}分`;
    };

    useEffect(() => {
        const removeListener = BluetoothManager.addConnectionStateListener((state) => {
            console.log('蓝牙连接状态变化:', state);
            setConnectionState(state);
            if (state === ConnectionState.DISCONNECTED) {
                hideWithAnimation();
            }
        });

        return () => {
            removeListener();
            BluetoothManager.disconnect();
            hideWithAnimation();
        };
    }, []);

    return (
        <>
            <View style={styles.infoBox}>
                <View style={styles.eleBox}>
                    <View style={[
                        styles.eleType,
                        {
                            height: `${defaultDevice?.remainingPower || 0}%`,
                            backgroundColor: getPowerColor(defaultDevice?.remainingPower || 0)
                        }
                    ]}>
                        <Text style={styles.eleTypeTxt}>{defaultDevice?.remainingPower || 0}%</Text>
                    </View>
                </View>
                <View style={styles.carBox}>
                    <Image
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uVnIDwcwQP7oo12PeYVJ' }}
                        style={{ width: rpx(440), height: rpx(340) }}
                    />
                    <View style={styles.txtbox}>
                        <View style={styles.yuan}></View>
                        <Text style={styles.txt}>当前车辆状态： {defaultDevice?.lockStatus == 1 ? '开锁' : '关锁'}</Text>
                    </View>
                    {defaultDevice?.type == 2 && defaultDevice?.expirationTime && (
                        <View style={styles.txtbox1}>
                            <Text style={styles.txt1}>
                                剩余有效期：{calculateTimeRemaining(defaultDevice.expirationTime)}
                            </Text>
                        </View>
                    )}
                </View>
                {showBluetoothStatus && (
                    <Animated.View
                        style={[
                            styles.switch,
                            {
                                opacity: fadeAnim,
                                transform: [{ translateX: slideAnim }]
                            }
                        ]}
                    >
                        {isConnecting ? (
                            <>
                                <Spinner size='small' status='warning' />
                                <Text style={[styles.statusText, styles.connecting]}>正在连接</Text>
                                <Image
                                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/ukhgaoFSHmlJWkgyC4U4' }}
                                    style={styles.bluetooth}
                                />
                            </>
                        ) : (
                            <>
                                <Text style={[styles.statusText, styles.connected]}>连接成功</Text>
                                <Image
                                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/udli5LEVfOT62XShk99A' }}
                                    style={styles.bluetooth}
                                />
                            </>
                        )}
                    </Animated.View>
                )}
            </View>

            <View style={styles.car_stause_box}>
                <TouchableOpacity
                    style={styles.car_stause_li}
                    onPress={handleRing}
                    disabled={isConnecting}
                >
                    <Image
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uro1vIU1WydjNWgi7PUg' }}
                        style={{ width: rpx(90), height: rpx(90), marginLeft: rpx(18) }}
                    />
                    <Text style={styles.stauseText}>鸣笛寻车</Text>
                </TouchableOpacity>

                {defaultDevice && (
                    <Slider
                        key={defaultDevice.sn}
                        lockStatus={Number(defaultDevice.lockStatus)}
                        onStatusChange={handleLockStatus}
                        disabled={isConnecting}
                        defaultDevice={defaultDevice}
                    />
                )}

                <View style={styles.car_stause_li}>
                    <Image
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uVpJNxwWXlyXt4IdHQoe' }}
                        style={{ width: rpx(90), height: rpx(90), marginLeft: rpx(18) }}
                    />
                    <Text style={styles.stauseText}>警报已开</Text>
                </View>
            </View>
        </>
    );
};

const styles = StyleSheet.create({
    infoBox: {
        marginTop: rpx(66),
        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    carBox: {
        width: rpx(440),
        position: 'absolute',
        top: rpx(20),
        left: rpx(124),
        zIndex: 0,
    },
    switch: {
        width: rpx(272),
        height: rpx(60),
        backgroundColor: '#FFFFFF',
        borderRadius: rpx(30),
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: rpx(20),
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 4,
    },
    statusText: {
        fontSize: rpx(32),
        fontWeight: '400',
        marginLeft: rpx(10),
    },
    connecting: {
        color: '#FF8282',
    },
    connected: {
        color: '#4297F3',
        marginLeft: rpx(40),
    },
    bluetooth: {
        width: rpx(60),
        height: rpx(60),
        marginLeft: 'auto',
    },
    Bind_type: {
        flexDirection: 'row',
        width: rpx(272),
        height: rpx(60),
        backgroundColor: '#fff',
        borderRadius: rpx(30),
        alignItems: 'center',
    },
    txtbox: {
        width: rpx(440),
        justifyContent: 'center',
        flexDirection: 'row',
        alignItems: 'center',
    },
    txtbox1: {
        marginTop: rpx(10),
        width: rpx(440),
        justifyContent: 'center',
        flexDirection: 'row',
        alignItems: 'center',
    },
    txt1: {
        marginLeft: rpx(14),
        fontSize: rpx(32),
        fontWeight: '400',
        color: '#3D3D3D',
    },
    txt: {
        marginLeft: rpx(14),
        fontSize: rpx(28),
        fontWeight: '400',
        color: '#3D3D3D',
    },
    yuan: {
        width: rpx(22),
        height: rpx(22),
        borderRadius: rpx(11),
        backgroundColor: 'rgba(255, 130, 130, 1)',
    },
    eleBox: {
        paddingTop: rpx(14),
        paddingRight: rpx(6),
        paddingBottom: rpx(6),
        paddingLeft: rpx(6),
        width: rpx(86),
        height: rpx(166),
        borderRadius: rpx(16),
        backgroundColor: '#FFFFFF',
        justifyContent: 'flex-end',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.1,
        shadowRadius: 4,
        elevation: 4,
        borderWidth: 1,
        borderColor: '#E0E0E0',
    },
    eleType: {
        width: '100%',
        minHeight: rpx(30),
        borderRadius: rpx(16),
        position: 'relative',
    },
    eleTypeTxt: {
        position: 'absolute',
        top: rpx(-40),
        width: '100%',
        textAlign: 'center',
        fontSize: rpx(32),
        color: '#3D3D3D',
        textShadowColor: 'rgba(255, 255, 255, 0.5)',
        textShadowOffset: { width: 0, height: 1 },
        textShadowRadius: 2
    },
    car_stause_box: {
        marginTop: rpx(308),
        flexDirection: 'row',
        justifyContent: 'space-around'
    },
    car_stause_li: {
        width: rpx(136),
        justifyContent: 'center'
    },
    stauseText: {
        fontSize: rpx(32),
        color: '#3D3D3D',
        textAlign: 'center',
        marginTop: rpx(24)
    },
});

export default DeviceControl;