import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';
import { RouteProp, useRoute, useNavigation } from '@react-navigation/native';
import { rpx } from '../../utils/rpx';
import { TopNavigation, TopNavigationAction, Icon } from '@ui-kitten/components';
import Toast from 'react-native-toast-message';
import { apiService } from '../../utils/api';

type RootStackParamList = {
    ConfirmBind: {
        sn: string;
    };
};

type ConfirmBindRouteProp = RouteProp<RootStackParamList, 'ConfirmBind'>;

interface DeviceInfo {
    model: string;    // 车型
    sn: string;       // 车辆编号
    version: string; // 固件信息
}

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

const ConfirmBind = () => {
    const route = useRoute<ConfirmBindRouteProp>();
    const navigation = useNavigation();
    const { sn } = route.params;
    const [deviceInfo, setDeviceInfo] = useState<DeviceInfo | null>(null);
    const [loading, setLoading] = useState(true);

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

    const BackAction = () => (
        <TopNavigationAction icon={BackIcon} onPress={navigateBack}/>
    );

    useEffect(() => {
        fetchDeviceInfo();
    }, []);

    const fetchDeviceInfo = async () => {
        try {
            setLoading(true);
            const response = await apiService.getDeviceInfo(sn);
            if (response.code === 200) {
                setDeviceInfo(response.data);
            } else {
                Toast.show({
                    type: 'error',
                    text1: response.msg || '获取设备信息失败',
                });
            }
        } catch (error) {
            Toast.show({
                type: 'error',
                text1: '获取设备信息失败',
            });
        } finally {
            setLoading(false);
        }
    };

    const handleConfirmBind = async () => {
        try {
            const response = await apiService.bindSn(sn);
            if (response.code === 200) {
                Toast.show({
                    type: 'success',
                text1: '绑定成功',
                });
                navigation.navigate('Home' as never);
            } else {
                Toast.show({
                    type: 'error',
                    text1: response.msg || '绑定失败',
                });
            }
        } catch (error) {
            console.log(error,'eeeeeeeeeeeeeeeee');
            Toast.show({
                type: 'error',
                text1: error.msg
            });
        }
    };
  
    return (
        <View style={styles.container}>
            <TopNavigation
                title='确认绑定'
                alignment='center'
                accessoryLeft={BackAction}
                style={styles.topNavigation}
            />

            <Image 
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uVnIDwcwQP7oo12PeYVJ' }} 
                style={styles.Image} 
            />

            {loading ? (
                <View style={styles.carInfo}>
                    <Text>加载中...</Text>
                </View>
            ) : deviceInfo ? (
                <View style={styles.carInfo}>
                    <View style={styles.carInfoItem}>
                        <Text style={styles.label}>车型</Text>
                        <Text style={styles.value}>{deviceInfo.model}</Text>
                    </View>
                    <View style={styles.carInfoItem}>
                        <Text style={styles.label}>车辆编号</Text>
                        <Text style={styles.value}>{deviceInfo.sn}</Text>
                    </View>
                    <View style={styles.carInfoItem}>
                        <Text style={styles.label}>固件信息</Text>
                        <Text style={styles.value}>{deviceInfo.version}</Text>
                    </View>
                </View>
            ) : (
                <View style={styles.carInfo}>
                    <Text>暂无设备信息</Text>
                </View>
            )}

            <TouchableOpacity 
                style={[
                    styles.buttons,
                    (!deviceInfo || loading) && styles.disabledButton
                ]}
                onPress={handleConfirmBind}
                disabled={loading || !deviceInfo}
            >
                <Text style={styles.buttonText}>确定绑定</Text>
            </TouchableOpacity>

            <Toast />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        position: 'relative',
        flex: 1, 
        backgroundColor: '#F3FCFF',
    },
    topNavigation: {
        backgroundColor: '#F3FCFF',
        elevation: 0,
        borderBottomWidth: 1,
        borderBottomColor: '#E8E8E8',
    },
    Image: {
        marginTop: rpx(40),
        width: rpx(440),
        height: rpx(340),
        alignSelf: 'center',
    },
    carInfo: {
        marginTop: rpx(40),
        padding: rpx(16),
        paddingLeft: rpx(42),
        paddingRight: rpx(42),
        width: rpx(688),
        backgroundColor: '#FFFFFF',
        borderRadius: rpx(30),
        alignSelf: 'center',
        minHeight: rpx(256),
        justifyContent: 'center',
        // iOS 阴影
        shadowColor: 'rgba(0, 0, 0, 0.1)',
        shadowOffset: {
            width: 0,
            height: rpx(2),
        },
        shadowOpacity: 1,
        shadowRadius: rpx(18),
        // Android 阴影
        elevation: 4,
    },
    carInfoItem: {
        marginTop: rpx(28),
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    label: {
        fontSize: rpx(28),
        color: '#666666',
    },
    value: {
        marginLeft: 'auto',
        fontSize: rpx(28),
        color: '#333333',
        fontWeight: '500',
        textAlign: 'right',
        minWidth: rpx(150),
    },
    buttons: {
        position: 'absolute',
        bottom: rpx(80),
        left: '50%',
        transform: [{ translateX: -rpx(307) }],
        width: rpx(614),
        height: rpx(92),
        backgroundColor: '#4297F3',
        borderRadius: rpx(20),
        justifyContent: 'center',
        alignItems: 'center',
    },
    disabledButton: {
        backgroundColor: '#B4B4B4',
    },
    buttonText: {
        color: '#FFFFFF',
        fontSize: rpx(32),
        fontWeight: 'bold',
    },
});

export default ConfirmBind;