import React, { useState } from 'react';
import { View, Text, StyleSheet, Image, TextInput, TouchableWithoutFeedback, Keyboard, TouchableOpacity, Modal } from 'react-native';
import { rpx } from '../../utils/rpx';
import { useNavigation, NavigationProp } from '@react-navigation/native';
import { apiService } from '../../utils/api';
import AsyncStorage from '@react-native-async-storage/async-storage';

type RootStackParamList = {
    ShareQrcode: {
        QrId: number;
    };
};
const AddShare = () => {
    const navigation = useNavigation<NavigationProp<RootStackParamList>>();

    const [phone, setPhone] = useState('');
    const [name, setName] = useState('');
    const [time, setTime] = useState('');
    const [showTimeModal, setShowTimeModal] = useState(false);
    const [showBleInfo, setShowBleInfo] = useState(false);
    const timeOptions = ['1天', '7天', '30天', '永久'];
    const [allowBleLocation, setAllowBleLocation] = useState(true);
    const handlePress = () => {
        setShowTimeModal(true);
    }
    const handleSubmit = async () => {
        try {
            // 获取存储的设备 SN
            const deviceSN = await AsyncStorage.getItem('defaultDeviceSN');
            
            if (!deviceSN) {
                console.error('未找到设备 SN');
                return;
            }

            // 获取当前时间
            const now = new Date();
            
            // 根据选择设置过期时间
            let expirationDate = new Date(now);
            switch (time) {
                case '1天':
                    expirationDate.setDate(now.getDate() + 1);
                    break;
                case '7天':
                    expirationDate.setDate(now.getDate() + 7);
                    break;
                case '30天':
                    expirationDate.setDate(now.getDate() + 30);
                    break;
                case '永久':
                    expirationDate.setFullYear(now.getFullYear() + 1); // 永久设置为一年
                    break;
                default:
                    console.error('无效的时间选择');
                    return;
            }

            // 设置时间为当天的 23:59:59
            expirationDate.setHours(23, 59, 59, 0);

            // 格式化日期为 YYYY-MM-DD HH:mm:ss
            const formatDate = (date: Date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            };

            // 表单验证
            if (!phone || !name || !time) {
                console.error('请填写完整信息');
                return;
            }

            const response = await apiService.addKey({
                sharePhone: phone,
                shareUserName: name,
                sn: deviceSN,
                expirationTime: formatDate(expirationDate)
            });
            console.log(response,'response');
            if (response?.code == 200) {
                // 添加成功，返回上一页
                navigation.goBack();
            } else {
                console.error('添加共享失败:', response?.message);
            }
        } catch (error) {
            console.error('添加共享失败:', error);
        }
    };
    
  
    return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <View style={styles.container}>
                <View style={styles.IptBox}>
                    <TextInput
                        style={styles.input}
                        placeholder="共享人手机号"
                        value={phone}
                        onChangeText={setPhone}
                    />
                    
                    <Image
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uMSABuH69gxKXIP0zqtl' }}
                        style={styles.phoneImg}
                    />
 
                </View>
                <View style={styles.IptBox}>
                    <TextInput
                        style={styles.input}
                        placeholder="共享人姓名"
                        value={name}
                        onChangeText={setName}
                    />
                </View>
                <TouchableOpacity onPress={handlePress} activeOpacity={1}>
                    <View style={styles.IptBox}>
                        <TextInput
                            style={styles.input}
                            placeholder="共享钥匙有效期"
                            value={time}
                            onChangeText={setTime}
                            editable={false}
                        />
                        <Image
                            source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uGq4yJlU1ZZRkwiJ8Y74' }}
                            style={styles.phoneImg}
                        />
                    </View>
                </TouchableOpacity>
                
                <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
                    <Text style={styles.submitButtonText}>确定</Text>
                </TouchableOpacity>
                <Modal
                    visible={showTimeModal}
                    transparent={true}
                    animationType="slide"
                >
                    <View style={styles.modalContainer}>
                        <View style={styles.modalContent}>
                            <View style={styles.modalHeader}>
                                <TouchableOpacity
                                    style={styles.headerButton}
                                    onPress={() => setShowTimeModal(false)}
                                >
                                    <Text style={styles.cancelText}>取消</Text>
                                </TouchableOpacity>
                                <Text style={styles.modalTitle}>选择有效期</Text>
                                <TouchableOpacity
                                    style={styles.headerButton}
                                    onPress={() => setShowTimeModal(false)}
                                >
                                    <Text style={styles.confirmText}>确定</Text>
                                </TouchableOpacity>
                            </View>
                          
                            <View style={styles.optionsContainer}>
                                {timeOptions.map((option, index) => (
                                    <TouchableOpacity
                                        key={index}
                                        style={[
                                            styles.optionItem,
                                            time === option && styles.selectedItemBg
                                        ]}
                                        onPress={() => {
                                            setTime(option);
                                            setShowTimeModal(false);
                                        }}
                                    >
                                        <Text style={[
                                            styles.optionText,
                                            time === option && styles.selectedOption
                                        ]}>
                                            {option}
                                        </Text>
                                    </TouchableOpacity>
                                ))}
                            </View>
                        </View>
                    </View>
                </Modal>
            </View>
        </TouchableWithoutFeedback>
    );
}

const styles = StyleSheet.create({
    submitButton: {
        width: rpx(688),
        height: rpx(88),
        backgroundColor: '#4297F3',
        borderRadius: rpx(16),
        justifyContent: 'center',
        alignItems: 'center',
        marginTop: rpx(50),
    },
    submitButtonText: {
        fontSize: rpx(32),
        color: '#fff',
        fontWeight: '500',
    },
    container: {
        flex: 1,
        backgroundColor: '#F3FCFF',
        alignItems: 'center',
    },
    modalContainers: {
        flex: 1,
        justifyContent: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        paddingHorizontal: rpx(30),
    },
    modalContents: {
        backgroundColor: '#fff',
        borderRadius: rpx(20),
        alignItems: 'center',
        paddingVertical: rpx(40),
        padding:rpx(28)
    },
    bleLocationImg: {
        width: rpx(338),
        height: rpx(338),
        marginBottom: rpx(30),
    },
    bleModalTitle: {
        fontSize: rpx(36),
        color: '#333',
        textAlign: 'center',
        lineHeight: rpx(50),
        marginBottom: rpx(40),
    },
    line: {
        borderWidth: rpx(1),
        borderColor: '#eee',
        marginBottom: rpx(28)
    },
    radioGroup: {
        width: '100%',
        paddingHorizontal: rpx(60),
        marginBottom: rpx(40),
        borderWidth: rpx(2),
        borderColor: '#eee',
        borderRadius: rpx(30),
        paddingTop: rpx(28)
    },
    radioItem: {
        
        justifyContent: 'space-between',
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: rpx(30),
    },
    radioCircle: {
        width: rpx(44),
        height: rpx(44),
        borderRadius: rpx(22),
        borderWidth: rpx(2),
        borderColor: '#4297F3',
        marginRight: rpx(20),
        justifyContent: 'center',
        alignItems: 'center',
    },
    radioSelected: {
        width: rpx(28),
        height: rpx(28),
        borderRadius: rpx(14),
        backgroundColor: '#4297F3',
    },
    radioText: {
        fontSize: rpx(32),
        color: '#333',
    },
    confirmButton: {
        width: rpx(560),
        height: rpx(88),
        backgroundColor: '#4297F3',
        borderRadius: rpx(44),
        justifyContent: 'center',
        alignItems: 'center',
    },
    confirmButtonText: {
        fontSize: rpx(32),
        color: '#fff',
        fontWeight: '500',
    },
    bleImg: {
        width: rpx(88),
        height: rpx(88),
    },
    tit: {
        fontSize: rpx(36),
        color: '#1E1D20',
    },
    txt: {
        fontSize: rpx(36),
        color: '#4297F3',
    },
    bleInfo: {
        marginTop: rpx(30),
        width: rpx(688),
        height: rpx(174),
        backgroundColor: '#ffffff',
        padding: rpx(44),
        flexDirection: 'row',
        // alignItems: 'center',
        // justifyContent: 'center',
    },
    bleInfoBox: {
        paddingLeft: rpx(20),
    },
    modalContainer: {
        flex: 1,
        justifyContent: 'flex-end',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalContent: {
        backgroundColor: '#fff',
        borderTopLeftRadius: rpx(20),
        borderTopRightRadius: rpx(20),
        paddingBottom: rpx(30),
    },
    modalHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: rpx(100),
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        paddingHorizontal: rpx(30),
    },
    headerButton: {
        padding: rpx(20),
    },
    modalTitle: {
        fontSize: rpx(32),
        fontWeight: '500',
        color: '#333',
    },
    cancelText: {
        fontSize: rpx(32),
        color: '#666',
    },
    confirmText: {
        fontSize: rpx(32),
        color: '#4297F3',
    },
    optionsContainer: {
        paddingHorizontal: rpx(30),
        paddingTop: rpx(20),
        alignItems: 'center',
    },
    optionItem: {
        height: rpx(100),
        width: rpx(300),
        justifyContent: 'center',
        alignItems: 'center',
        // paddingLeft: rpx(30),
        borderRadius: rpx(16),
        marginBottom: rpx(20),
    },
    optionText: {
        fontSize: rpx(32),
        color: '#333',
    },
    selectedItemBg: {
        backgroundColor: '#F0F7FF',
    },
    selectedOption: {
        color: '#4297F3',
    },
    IptBox: {
        marginTop: rpx(30),
        paddingHorizontal: rpx(30),
        width: rpx(688),
        height: rpx(128),
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#ffffff',
        borderRadius: rpx(30),

    },
    input: {
        flex: 1,
        fontSize: rpx(36),
    },
    phoneImg: {
        width: rpx(54),
        height: rpx(54),
    }
})
export default AddShare;