import React, { useState } from 'react';
import {
    View,
    StyleSheet,
    TextInput,
    TouchableWithoutFeedback,
    Keyboard,
    Text,
    TouchableOpacity,
    Image,
    Modal
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { rpx } from '../../utils/rpx';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { RNCamera } from 'react-native-camera';
import { TopNavigation, TopNavigationAction, Icon, Popover, Button } from '@ui-kitten/components';
import Toast from 'react-native-toast-message';
import { launchImageLibrary } from 'react-native-image-picker';
import QRReader from 'rn-qr-generator';
import { apiService } from '../../utils/api';

type RootStackParamList = {
    Home: undefined;
    DeviceList: undefined;
    BindIndex: undefined;
    SnBind: undefined;
    ConfirmBind: {
        sn: string;
    };
};

type NavigationProp = StackNavigationProp<RootStackParamList>;

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

const SnBind = () => {
    const navigation = useNavigation<NavigationProp>();
    const [sn, setSn] = useState('');
    const [isScanning, setIsScanning] = useState(false);
    const [popoverVisible, setPopoverVisible] = useState(false);

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

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

    const togglePopover = () => {
        setPopoverVisible(!popoverVisible);
    };

    // 处理 keyId 的方法
    const handleKeyId = async (keyId: string) => {
        try {
            // 先获取用户信息
            const userInfoRes = await new Promise((resolve, reject) => {
                apiService.getUserInfo()
                    .then(res => {
                        if (!res || !res.user) {
                            Toast.show({
                                type: 'error',
                                text1: '获取用户信息失败',
                            });
                            reject(new Error('获取用户信息失败'));
                            return;
                        }
                        resolve(res);
                    })
                    .catch(error => {
                        console.error('获取用户信息出错:', error);
                        Toast.show({
                            type: 'error',
                            text1: '获取用户信息失败',
                        });
                        reject(error);
                    });
            });
    
            // 用户信息获取成功后，再获取密钥信息
            const keyInfoRes = await new Promise((resolve, reject) => {
                apiService.getKeyInfo(keyId)
                    .then(res => {
                        if (!res || !res.data) {
                            Toast.show({
                                type: 'error',
                                text1: '二维码已过期',
                            });
                            reject(new Error('二维码已过期'));
                            return;
                        }
                        resolve(res);
                    })
                    .catch(error => {
                        console.error('获取密钥信息出错:', error);
                        Toast.show({
                            type: 'error',
                            text1: '获取密钥信息失败',
                        });
                        reject(error);
                    });
            });
    
            // 验证手机号匹配
            const userPhone = userInfoRes.user.phonenumber;
            const sharePhone = keyInfoRes.data.sharePhone;
    
            if (!userPhone || !sharePhone) {
                Toast.show({
                    type: 'error',
                    text1: '手机号信息不完整',
                });
                return;
            }
    
            if (userPhone !== sharePhone) {
                Toast.show({
                    type: 'error',
                    text1: '您不是分享码的拥有者',
                });
                return;
            }
    
            // 执行绑定操作
            const bindRes = await new Promise((resolve, reject) => {
                apiService.bindKey(keyId)
                    .then(res => {
                        if (res.code === 200) {
                            Toast.show({
                                type: 'success',
                                text1: '绑定成功',
                            });
                            navigateBack();
                            resolve(res);
                        } else {
                            Toast.show({
                                type: 'error',
                                text1: res.msg || '绑定失败',
                            });
                            reject(new Error(res.msg || '绑定失败'));
                        }
                    })
                    .catch(error => {
                        console.error('绑定密钥出错:', error);
                        Toast.show({
                            type: 'error',
                            text1: '绑定失败',
                        });
                        reject(error);
                    });
            });
    
        } catch (error) {
            console.error('处理密钥绑定时出错:', error);
            Toast.show({
                type: 'error',
                text1: '操作失败，请稍后重试',
            });
        }
    };

    // 处理扫描结果的方法
    const handleScanResult = (data: string) => {
        // console.log('扫描结果:', data);
        try {
            // 检查是否包含 sn
            const snMatch = data.match(/[?&]sn=([^&]+)/);
            if (snMatch && snMatch[1]) {
                setSn(snMatch[1]);
                setIsScanning(false);
                Toast.show({
                    type: 'success',
                    text1: '扫描成功',
                });
                // 自动触发确认绑定
                navigation.navigate('ConfirmBind', { sn: snMatch[1].trim() });
                return;
            }

            // 检查是否包含 keyId
            const keyIdMatch = data.match(/[?&]keyId=([^&]+)/);

            if (keyIdMatch && keyIdMatch[1]) {

                setIsScanning(false);
                handleKeyId(keyIdMatch[1]);
                return;
            }

            Toast.show({
                type: 'error',
                text1: '未找到有效的识别码',
            });
        } catch (error) {
            Toast.show({
                type: 'error',
                text1: '二维码解析失败',
            });
        }
    };

    const handlePress = () => {
        if (!sn.trim()) {
            Toast.show({
                type: 'error',
                text1: '请输入SN码',
            });
            return;
        }
        navigation.navigate('ConfirmBind', { sn: sn.trim() });
    };

    const handleImagePicker = () => {
        setPopoverVisible(false);
        launchImageLibrary({
            mediaType: 'photo',
            quality: 1,
        }, async (response) => {
            if (response.didCancel) {
                console.log('User cancelled image picker');
            } else if (response.errorCode) {
                console.log('ImagePicker Error: ', response.errorMessage);
            } else if (response.assets && response.assets.length > 0) {
                try {
                    const { uri } = response.assets[0];

                    // 使用 QRReader 识别图片中的二维码
                    const result = await QRReader.detect({
                        uri: uri
                    });

                    if (result.values && result.values.length > 0) {
                        const qrData = result.values[0];
                        handleScanResult(qrData);
                    } else {
                        Toast.show({
                            type: 'error',
                            text1: '图片中未检测到二维码',
                        });
                    }
                } catch (error) {
                    console.error('扫描错误:', error);
                    Toast.show({
                        type: 'error',
                        text1: '图片解析失败',
                    });
                }
            }
        });
    };

    const onSuccess = (e: { data: string }) => {
        handleScanResult(e.data);
    };

    return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <View style={styles.container}>
                <TopNavigation
                    title='绑定设备'
                    alignment='center'
                    accessoryLeft={BackAction}
                    style={styles.topNavigation}
                />

                <View style={styles.contentArea}>
                    {/* 顶部图片 */}
                    <Image
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uVnIDwcwQP7oo12PeYVJ' }}
                        style={styles.topImage}
                    />

                    {/* 输入框和扫码按钮 */}
                    <View style={styles.IptBox}>
                        <TextInput
                            style={styles.input}
                            placeholder="请输入SN"
                            value={sn}
                            onChangeText={setSn}
                        />
                        <Popover
                            anchor={() => (
                                <TouchableOpacity onPress={togglePopover} style={styles.scanButton}>
                                    <Image
                                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uSPtEFPtKlWIAKNrDtiQ' }}
                                        style={styles.scanIcon}
                                    />
                                </TouchableOpacity>
                            )}
                            visible={popoverVisible}
                            onBackdropPress={togglePopover}
                        >
                            <View>
                                <Button onPress={handleImagePicker}>从相册选择</Button>
                                <Button onPress={() => {
                                    setPopoverVisible(false);
                                    setIsScanning(true);
                                }}>扫描二维码</Button>
                            </View>
                        </Popover>
                    </View>

                    {/* 提示文本 */}
                    <View style={styles.tip}>
                        <View style={styles.yuan}></View>
                        <Text style={styles.txt}>输入对应二维码下方的激活码或扫描二维码</Text>
                    </View>

                    {/* 确认按钮 */}
                    <TouchableOpacity onPress={handlePress}>
                        <View style={styles.addcar}>
                            <Text style={styles.addTxt}>确认绑定</Text>
                        </View>
                    </TouchableOpacity>
                </View>

                {/* 扫码Modal */}
                <Modal
                    visible={isScanning}
                    onRequestClose={() => setIsScanning(false)}
                    animationType="slide"
                    statusBarTranslucent={true}
                >
                    <View style={styles.modalContainer}>
                        <TopNavigation
                            title='扫描二维码'
                            alignment='center'
                            accessoryLeft={() => (
                                <TopNavigationAction
                                    icon={BackIcon}
                                    onPress={() => setIsScanning(false)}
                                />
                            )}
                            style={styles.scannerTopNav}
                        />
                        <QRCodeScanner
                            onRead={onSuccess}
                            flashMode={RNCamera.Constants.FlashMode.auto}
                            topContent={
                                <View style={styles.headerContainer}>
                                    <Text style={styles.scanSubTitle}>
                                        将二维码放入框内，即可自动扫描
                                    </Text>
                                </View>
                            }
                            bottomContent={
                                <View style={styles.bottomContainer}>
                                    <TouchableOpacity
                                        style={styles.cancelButton}
                                        onPress={() => setIsScanning(false)}
                                    >
                                        <Text style={styles.cancelButtonText}>取消扫描</Text>
                                    </TouchableOpacity>
                                </View>
                            }
                            containerStyle={styles.scannerContainer}
                            cameraStyle={styles.cameraContainer}
                            cameraProps={{
                                captureAudio: false,
                                androidCameraPermissionOptions: {
                                    title: '相机权限',
                                    message: '我们需要使用您的相机来扫描二维码',
                                    buttonPositive: '确定',
                                    buttonNegative: '取消',
                                },
                                barCodeTypes: [RNCamera.Constants.BarCodeType.qr],
                            }}
                        />
                    </View>
                </Modal>
                <Toast />
            </View>
        </TouchableWithoutFeedback>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F3FCFF',
    },
    topNavigation: {
        backgroundColor: '#F3FCFF',
        elevation: 0,
        borderBottomWidth: 1,
        borderBottomColor: '#E8E8E8',
    },
    contentArea: {
        flex: 1,
        alignItems: 'center',
        paddingTop: rpx(40),
    },
    topImage: {
        width: rpx(440),
        height: rpx(340),
        marginBottom: rpx(40),
        resizeMode: 'contain',
    },
    IptBox: {
        width: rpx(688),
        height: rpx(128),
        borderRadius: rpx(30),
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.1,
        shadowRadius: 3,
        elevation: 3,
    },
    input: {
        flex: 1,
        paddingHorizontal: rpx(30),
        fontSize: rpx(28),
    },
    scanButton: {
        height: rpx(128),
        width: rpx(128),
        borderRadius: rpx(30),
        backgroundColor: '#4297F3',
        alignItems: 'center',
        justifyContent: 'center',
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.3,
        shadowRadius: 4,
        elevation: 5,
    },
    scanIcon: {
        width: rpx(88),
        height: rpx(88),
        resizeMode: 'contain',
        tintColor: '#fff',
    },
    tip: {
        marginTop: rpx(40),
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: rpx(32),
        width: rpx(688),
    },
    yuan: {
        width: rpx(12),
        height: rpx(12),
        borderRadius: rpx(6),
        backgroundColor: '#FF8282',
        marginRight: rpx(14),
    },
    txt: {
        fontWeight: '400',
        color: '#3D3D3D',
        fontSize: rpx(28),
    },
    addcar: {
        width: rpx(641),
        height: rpx(92),
        marginTop: rpx(122),
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#4297F3',
        borderRadius: rpx(20),
        shadowColor: '#4297F3',
        shadowOffset: {
            width: 0,
            height: 4,
        },
        shadowOpacity: 0.3,
        shadowRadius: 5,
        elevation: 5,
    },
    addTxt: {
        fontWeight: '500',
        color: '#ffffff',
        fontSize: rpx(36),
    },
    modalContainer: {
        flex: 1,
        backgroundColor: '#000',
    },
    scannerContainer: {
        flex: 1,
    },
    scannerTopNav: {
        backgroundColor: 'transparent',
    },
    headerContainer: {
        alignItems: 'center',
        padding: rpx(40),
        backgroundColor: 'transparent',
    },
    scanSubTitle: {
        fontSize: rpx(28),
        color: '#ffffff',
        opacity: 0.8,
    },
    bottomContainer: {
        width: '100%',
        alignItems: 'center',
        paddingBottom: rpx(40),
    },
    cancelButton: {
        backgroundColor: '#ffffff',
        paddingHorizontal: rpx(60),
        paddingVertical: rpx(24),
        borderRadius: rpx(40),
        marginTop: rpx(40),
    },
    cancelButtonText: {
        fontSize: rpx(32),
        color: '#333333',
        fontWeight: '500',
    },
    cameraContainer: {
        height: rpx(800),
    },
});

export default SnBind;