import React, { useState, useEffect } from 'react';
import { View, StyleSheet, ImageBackground, Text, TouchableOpacity, Modal, TextInput, ActivityIndicator, Button, Image, ScrollView } from 'react-native';
import { TopNavigation, TopNavigationAction, Icon, IconElement, Select, SelectItem, IndexPath } from '@ui-kitten/components';
import { useNavigation } from '@react-navigation/native';
import { rpx } from '../../utils/rpx';
import { apiService } from '../../utils/api';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Toast from 'react-native-toast-message';
import { uploadImageService } from '../../utils/uploadImg';

const BackIcon = (props): IconElement => (
    <Icon
        {...props}
        name='arrow-back'
        fill='#000000'
    />
);

interface EditModalProps {
    visible: boolean;
    onClose: () => void;
    title: string;
    value: string;
    onSubmit: (value: string) => void;
    placeholder?: string;
}

const EditModal: React.FC<EditModalProps> = ({
    visible,
    onClose,
    title,
    value,
    onSubmit,
    placeholder
}) => {
    const [inputValue, setInputValue] = useState(value);

    useEffect(() => {
        setInputValue(value);
    }, [value]);

    const handleSubmit = () => {
        onSubmit(inputValue);
    };

    return (
        <Modal
            visible={visible}
            transparent={true}
            animationType="fade"
            onRequestClose={onClose}
        >
            <View style={styles.modalOverlay}>
                <View style={styles.modalContent}>
                    <Text style={styles.modalTitle}>{title}</Text>
                    <TextInput
                        style={styles.modalInput}
                        value={inputValue}
                        onChangeText={setInputValue}
                        placeholder={placeholder}
                        placeholderTextColor="#999999"
                    />
                    <View style={styles.modalButtons}>
                        <TouchableOpacity style={styles.modalButton} onPress={onClose}>
                            <Text style={styles.modalButtonText}>取消</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={[styles.modalButton, styles.modalButtonPrimary]} onPress={handleSubmit}>
                            <Text style={[styles.modalButtonText, styles.modalButtonTextPrimary]}>确定</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        </Modal>
    );
};

const deviceDetailSet = () => {
    const navigation = useNavigation();
    const [modalVisible, setModalVisible] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [deviceInfo, setDeviceInfo] = useState<any>(null);
    const [currentEdit, setCurrentEdit] = useState<{
        title: string;
        value: string;
        type: 'remark' | 'fullVoltage' | 'vehicleNum' | 'lowVoltage' | 'fullEndurance';
    } | null>(null);

    const [modelData, setModelData] = useState([]);
    const [selectedBrandIndex, setSelectedBrandIndex] = useState<IndexPath | null>(null);
    const [selectedModelIndex, setSelectedModelIndex] = useState<IndexPath | null>(null);
    const [brandList, setBrandList] = useState([]);
    const [modelList, setModelList] = useState([]);
    const [modelModalVisible, setModelModalVisible] = useState(false);

    const upload = async () => {
        try {
            const result = await uploadImageService.uploadImage();
    
            if (!result || !Array.isArray(result) || result.length === 0) {
                Toast.show({
                    type: 'error',
                    text1: '上传失败',
                    text2: '请重试',
                });
                return;
            }
    
            const imageUrl = result[0]; // 从数组中提取 URL
    
            const response = await apiService.updateDevice({
                sn: deviceInfo.sn,
                pricture: imageUrl
            });
    
            if (response.code == 200) {
                setDeviceInfo(prevInfo => ({
                    ...prevInfo,
                    pricture: imageUrl
                }));
                setModalVisible(false);
                Toast.show({
                    type: 'success',
                    text1: '修改成功',
                });
                fetchDeviceInfo();
            } else {
                Toast.show({
                    type: 'error',
                    text1: response.msg || '修改失败',
                });
            }
        } catch (error) {
            console.error('Update failed:', error);
            Toast.show({
                type: 'error',
                text1: '更新失败',
                text2: '请检查网络连接',
            });
        }
    };

    const fetchDeviceInfo = async () => {
        setIsLoading(true);
        try {
            const sn = await AsyncStorage.getItem('defaultDeviceSN');
            if (!sn) {
                Toast.show({
                    type: 'error',
                    text1: '未找到设备信息',
                });
                return;
            }

            const response = await apiService.getDeviceInfo(sn);
            if (response.code == 200 && response.data) {
                setDeviceInfo(response.data);
            } else {
                Toast.show({
                    type: 'error',
                    text1: response.msg || '获取设备信息失败',
                });
            }
        } catch (error) {
            console.error('获取设备信息错误:', error);
            Toast.show({
                type: 'error',
                text1: '获取设备信息失败',
                text2: '请检查网络连接',
            });
        } finally {
            setIsLoading(false);
        }
    };

    const fetchModelList = async () => {
        const response = await apiService.getModelList();
        if (response.code === 200) {
            setModelData(response.data);
            const brands = Array.from(new Set(response.data.map(item => item.brandName)));
            setBrandList(brands);
            setSelectedBrandIndex(new IndexPath(0));
            filterModels(brands[0]);
        }
    };

    const filterModels = (brand) => {
        const models = modelData.filter(item => item.brandName === brand).map(item => item.model);
        setModelList(models);
        setSelectedModelIndex(new IndexPath(0));
    };

    const getImageUrl = (brand, model) => {
        const selectedModel = modelData.find(item => item.brandName === brand && item.model === model);
        return selectedModel ? selectedModel.picture : null;
    };

    const updateDeviceImage = async (brand, model) => {
        const imageUrl = getImageUrl(brand, model);
        if (imageUrl && deviceInfo?.sn) {
            try {
                const response = await apiService.updateDevice({
                    sn: deviceInfo.sn,
                    pricture: imageUrl
                });
                console.log(response,'图片上传');
                if (response.code == 200) {
                    setDeviceInfo(prevInfo => ({
                        ...prevInfo,
                        pricture: imageUrl
                    }));
                    Toast.show({
                        type: 'success',
                        text1: '图片更新成功',
                    });
                } else {
                    Toast.show({
                        type: 'error',
                        text1: response.msg || '图片更新失败',
                    });
                }
            } catch (error) {
                console.error('图片更新失败:', error);
                Toast.show({
                    type: 'error',
                    text1: '图片更新失败',
                    text2: '请检查网络连接',
                });
            }
        }
    };

    const handleBrandChange = (index) => {
        setSelectedBrandIndex(index);
        const brand = brandList[index.row];
        filterModels(brand);
    };

    const handleModelChange = (index) => {
        setSelectedModelIndex(index);
    };

    const handleModelSelection = () => {
        const brand = brandList[selectedBrandIndex.row];
        const model = modelList[selectedModelIndex.row];
        updateDeviceImage(brand, model);
        setModelModalVisible(false);
    };

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

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

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

    const handleEdit = (type: 'remark' | 'fullVoltage' | 'vehicleNum' | 'lowVoltage' | 'fullEndurance') => {
        let title = '';
        let value = '';

        switch (type) {
            case 'remark':
                title = '修改备注';
                value = deviceInfo?.remark || '';
                break;
            case 'fullVoltage':
                title = '修改满电电压';
                value = deviceInfo?.fullVoltage || '';
                break;
            case 'vehicleNum':
                title = '修改车牌号';
                value = deviceInfo?.vehicleNum || '';
                break;
            case 'lowVoltage':
                title = '修改亏电电压';
                value = deviceInfo?.lowVoltage || '';
                break;
            case 'fullEndurance':
                title = '修改满电续航';
                value = deviceInfo?.fullEndurance || '';
                break;
        }

        setCurrentEdit({ title, value, type });
        setModalVisible(true);
    };

    const handleSubmit = async (value: string) => {
        if (!currentEdit || !deviceInfo?.sn) return;

        try {
            const response = await apiService.updateDevice({
                sn: deviceInfo.sn,
                [currentEdit.type]: value
            });

            if (response.code === 200) {
                setDeviceInfo(prevInfo => ({
                    ...prevInfo,
                    [currentEdit.type]: value
                }));
                setModalVisible(false);
                Toast.show({
                    type: 'success',
                    text1: '修改成功',
                });
                fetchDeviceInfo();
            } else {
                Toast.show({
                    type: 'error',
                    text1: response.msg || '修改失败',
                });
            }
        } catch (error) {
            console.error('Update failed:', error);
            Toast.show({
                type: 'error',
                text1: '更新失败',
                text2: '请检查网络连接',
            });
        }
    };

    const handleUnbind = () => {
        apiService.untieDevice(deviceInfo.deviceId).then((res) => {
            if (res.code == 200) {
                Toast.show({
                    type: 'success',
                    text1: '解绑成功',
                });
                navigation.goBack();
            }
        });
    };

    if (isLoading) {
        return (
            <View style={styles.loadingContainer}>
                <ActivityIndicator size="large" color="#333333" />
            </View>
        );
    }

    return (
        <View style={styles.container}>
            <TopNavigation
                title='设备设置'
                alignment='center'
                accessoryLeft={BackAction}
                style={styles.header}
            />
            <ScrollView
                contentContainerStyle={styles.scrollContent}
                scrollEventThrottle={16}
                nestedScrollEnabled={true}
            >

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

                    <ImageBackground
                        source={{ uri: 'https://lxnapi.ccttiot.com/FqAu65KgcylSRv1pD4008a_Ctpz-' }}
                        style={styles.carInfo}
                    >
                        <Image source={{ uri: deviceInfo?.pricture ? deviceInfo?.pricture : 'https://lxnapi.ccttiot.com/bike/img/static/uVnIDwcwQP7oo12PeYVJ' }} style={{ width: rpx(440), height: rpx(340) }} />
                        <View style={styles.carInfoButtons}>
                            <TouchableOpacity style={styles.carInfoButton} onPress={upload} >
                                <Text style={styles.carInfoButtonText}>上传图片</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[styles.carInfoButton, styles.carInfoButtonPrimary]} onPress={() => setModelModalVisible(true)}>
                                <Text style={[styles.carInfoButtonText, styles.carInfoButtonTextPrimary]}>匹配车辆</Text>
                            </TouchableOpacity>
                        </View>
                    </ImageBackground>
                    <View style={styles.infoContainer}>

                        <View style={styles.infoItem}>
                            <Text style={styles.label}>备注</Text>
                            <TouchableOpacity
                                style={styles.valueContainer}
                                onPress={() => handleEdit('remark')}
                            >
                                <Text style={styles.value}>{deviceInfo?.remark || '未设置'}</Text>
                                <Icon name='chevron-right' fill='#999999' style={styles.arrow} />
                            </TouchableOpacity>
                        </View>

                        <View style={styles.infoItem}>
                            <Text style={styles.label}>满电电压</Text>
                            <TouchableOpacity
                                style={styles.valueContainer}
                                onPress={() => handleEdit('fullVoltage')}
                            >
                                <Text style={styles.value}>{deviceInfo?.fullVoltage || '未设置'}</Text>
                                <Icon name='chevron-right' fill='#999999' style={styles.arrow} />
                            </TouchableOpacity>
                        </View>
                        <View style={styles.infoItem}>
                            <Text style={styles.label}>亏电电压</Text>
                            <TouchableOpacity
                                style={styles.valueContainer}
                                onPress={() => handleEdit('lowVoltage')}
                            >
                                <Text style={styles.value}>{deviceInfo?.lowVoltage || '未设置'}</Text>
                                <Icon name='chevron-right' fill='#999999' style={styles.arrow} />
                            </TouchableOpacity>
                        </View>
                        <View style={styles.infoItem}>
                            <Text style={styles.label}>满电续航</Text>
                            <TouchableOpacity
                                style={styles.valueContainer}
                                onPress={() => handleEdit('fullEndurance')}
                            >
                                <Text style={styles.value}>{deviceInfo?.fullEndurance || '未设置'}</Text>
                                <Icon name='chevron-right' fill='#999999' style={styles.arrow} />
                            </TouchableOpacity>
                        </View>
                        <View style={styles.infoItem}>
                            <Text style={styles.label}>车牌号</Text>
                            <TouchableOpacity
                                style={styles.valueContainer}
                                onPress={() => handleEdit('vehicleNum')}
                            >
                                <Text style={styles.value}>{deviceInfo?.vehicleNum || '未设置'}</Text>
                                <Icon name='chevron-right' fill='#999999' style={styles.arrow} />
                            </TouchableOpacity>
                        </View>
                        <View style={styles.infoItem}>
                            <Text style={styles.label}>蓝牙设置</Text>
                            <TouchableOpacity
                                style={styles.valueContainer}
                                onPress={() => navigation.navigate('DeviceSet')}
                            >
                                <Text style={styles.value}>去设置</Text>
                                <Icon name='chevron-right' fill='#999999' style={styles.arrow} />
                            </TouchableOpacity>
                        </View>

                    </View>

                    <TouchableOpacity style={styles.unbindButton} onPress={handleUnbind}>
                        <Text style={styles.unbindText}>车辆解绑</Text>
                    </TouchableOpacity>

                    {currentEdit && (
                        <EditModal
                            visible={modalVisible}
                            onClose={() => setModalVisible(false)}
                            title={currentEdit.title}
                            value={currentEdit.value}
                            onSubmit={handleSubmit}
                            placeholder={`请输入${currentEdit.title.slice(2)}`}
                        />
                    )}

                    <Modal
                        visible={modelModalVisible}
                        transparent={true}
                        animationType="slide"
                        onRequestClose={() => setModelModalVisible(false)}
                    >
                        <View style={styles.modalOverlay}>
                            <View style={styles.modalContent}>
                                <Text style={styles.modalTitle}>选择车型</Text>
                                <Image
                                    source={{ uri: getImageUrl(brandList[selectedBrandIndex?.row], modelList[selectedModelIndex?.row]) || 'https://lxnapi.ccttiot.com/bike/img/static/uVnIDwcwQP7oo12PeYVJ' }}
                                    style={styles.modalImage}
                                />
                                <Select
                                    selectedIndex={selectedBrandIndex}
                                    onSelect={handleBrandChange}
                                    style={styles.select}
                                    value={brandList[selectedBrandIndex?.row]}
                                >
                                    {brandList.map((brand, index) => (
                                        <SelectItem key={index} title={brand} />
                                    ))}
                                </Select>
                                <Select
                                    selectedIndex={selectedModelIndex}
                                    onSelect={handleModelChange}
                                    style={styles.select}
                                    value={modelList[selectedModelIndex?.row]}
                                >
                                    {modelList.map((model, index) => (
                                        <SelectItem key={index} title={model} />
                                    ))}
                                </Select>
                                <View style={styles.modalButtons}>
                                    <TouchableOpacity style={styles.modalButton} onPress={handleModelSelection}>
                                        <Text style={styles.modalButtonText}>确定</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={styles.modalButton} onPress={() => setModelModalVisible(false)}>
                                        <Text style={styles.modalButtonText}>关闭</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        </View>
                    </Modal>
                </ImageBackground>
            </ScrollView>
        </View>
    );
};

const styles = StyleSheet.create({
    scrollContent: {
        flexGrow: 1,
    },
    container: {
        flex: 1,
    },
    imageBackground: {
        paddingTop: rpx(40),
        paddingBottom: rpx(60),
        flex: 1,
        width: '100%',
        height: '100%',
    },
    carInfo: {
        paddingTop: rpx(180),
        width: '100%',
        height: rpx(828),
        alignItems: 'center',
    },
    carInfoButtons: {
        marginTop: rpx(160),
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '80%',
    },
    carInfoButton: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        width: rpx(250),
        height: rpx(80),
        backgroundColor: '#ffffff',
        borderRadius: rpx(20),
        borderWidth: rpx(2),
        borderColor: '#808080',
    },
    carInfoButtonPrimary: {
        borderRadius: rpx(20),
        backgroundColor: '#333333',
    },
    carInfoButtonText: {
        color: '#333333',
        fontSize: rpx(32),
        fontWeight: '500',
    },
    carInfoButtonTextPrimary: {
        color: '#FFFFFF',
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFFFFF',
    },
    header: {
        backgroundColor: 'transparent',
        elevation: 0,
        shadowOpacity: 0,
    },
    titleStyle: {
        color: '#000000',
        fontSize: rpx(36),
        fontWeight: 'bold',
    },
    infoContainer: {
        marginTop: rpx(40),
        marginHorizontal: rpx(32),
        backgroundColor: '#FFFFFF',
        borderRadius: rpx(20),
        padding: rpx(20),
    },
    infoItem: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: rpx(24),
        borderBottomWidth: 1,
        borderBottomColor: '#F5F5F5',
    },
    label: {
        fontSize: rpx(28),
        color: '#333333',
    },
    valueContainer: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    value: {
        fontSize: rpx(28),
        color: '#999999',
        marginRight: rpx(8),
    },
    arrow: {
        width: rpx(32),
        height: rpx(32),
    },
    unbindButton: {
        marginHorizontal: rpx(32),
        marginTop: rpx(40),
        height: rpx(88),
        backgroundColor: '#333333',
        borderRadius: rpx(20),
        justifyContent: 'center',
        alignItems: 'center',
    },
    unbindText: {
        color: '#FFFFFF',
        fontSize: rpx(32),
        fontWeight: '500',
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContent: {
        width: rpx(650),
        backgroundColor: '#FFFFFF',
        borderRadius: rpx(20),
        padding: rpx(40),
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5,
    },
    modalTitle: {
        fontSize: rpx(36),
        color: '#333333',
        fontWeight: 'bold',
        marginBottom: rpx(40),
        textAlign: 'center',
    },
    modalInput: {
        height: rpx(88),
        borderWidth: 1,
        borderColor: '#E5E5E5',
        borderRadius: rpx(12),
        paddingHorizontal: rpx(24),
        fontSize: rpx(28),
        color: '#333333',
        marginBottom: rpx(32),
    },
    modalButtons: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginTop: rpx(20),
    },
    modalButton: {
        flex: 1,
        height: rpx(88),
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: rpx(12),
        marginHorizontal: rpx(8),
        backgroundColor: '#F5F5F5',
    },
    modalButtonPrimary: {
        backgroundColor: '#333333',
    },
    modalButtonText: {
        fontSize: rpx(28),
        color: '#333333',
    },
    modalButtonTextPrimary: {
        color: '#FFFFFF',
    },
    select: {
        marginBottom: rpx(20),
    },
    modalImage: {
        width: rpx(440),
        height: rpx(340),
        marginBottom: rpx(20),
    },
});

export default deviceDetailSet;