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

interface KeyItem {
    keyId: string;
    avatarUrl: string;
    shareUserName: string;
    sharePhone: string;
    status: string;
    expirationTime: string;
    createTime: string;
}

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

const KeyDetail = () => {
    const navigation = useNavigation();
    const route = useRoute();
    const keyId = route.params?.keyItem.keyId;
    const [keyItem, setKeyItem] = useState<KeyItem | null>(null);
    const [visible, setVisible] = useState(false);
    const [showTimeModal, setShowTimeModal] = useState(false);
    const [selectedTime, setSelectedTime] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const timeOptions = ['1天', '7天', '30天', '永久'];

    // 获取钥匙详情
    const fetchKeyInfo = async () => {
        try {
            setIsLoading(true);
            const response = await apiService.getKeyInfo(keyId);
            if (response.code === 200 && response.data) {
                setKeyItem(response.data);
            } else {
                Toast.show({
                    type: 'error',
                    text1: '获取钥匙信息失败',
                });
            }
        } catch (error) {
            console.error('获取钥匙信息错误:', error);
            Toast.show({
                type: 'error',
                text1: '获取钥匙信息失败',
            });
        } finally {
            setIsLoading(false);
        }
    };

    // 组件挂载和 keyId 变化时获取数据
    useEffect(() => {
        if (keyId) {
            fetchKeyInfo();
        }
    }, [keyId]);

    const showDeleteModal = () => setVisible(true);
    const hideDeleteModal = () => setVisible(false);

    const handleDelete = async () => {
        try {
            setIsLoading(true);
            const res = await apiService.deleteKey(keyId);
            if (res.code === 200) {
                Toast.show({
                    type: 'success',
                    text1: '删除成功',
                });
                navigation.goBack();
            } else {
                Toast.show({
                    type: 'error',
                    text1: res.msg || '删除失败',
                });
            }
        } catch (error) {
            console.error('删除钥匙错误:', error);
            Toast.show({
                type: 'error',
                text1: '删除失败',
            });
        } finally {
            setIsLoading(false);
            hideDeleteModal();
        }
    };

    const handleTimeSelect = async (time: string) => {
        setSelectedTime(time);

        if (!keyItem) return;

        let days = 0;
        switch (time) {
            case '1天': days = 1; break;
            case '7天': days = 7; break;
            case '30天': days = 30; break;
            case '永久': days = 36500; break;
        }

        // 使用当前时间作为基准
        const now = new Date();
        const newExpirationDate = new Date(now.getTime() + days * 24 * 60 * 60 * 1000);

        // 设置为当天的最后一秒
        newExpirationDate.setHours(23);
        newExpirationDate.setMinutes(59);
        newExpirationDate.setSeconds(59);

        const formattedDate = newExpirationDate.getFullYear() + '-' +
            String(newExpirationDate.getMonth() + 1).padStart(2, '0') + '-' +
            String(newExpirationDate.getDate()).padStart(2, '0') + ' ' +
            String(newExpirationDate.getHours()).padStart(2, '0') + ':' +
            String(newExpirationDate.getMinutes()).padStart(2, '0') + ':' +
            String(newExpirationDate.getSeconds()).padStart(2, '0');

        try {
            setIsLoading(true);
            const res = await apiService.updateKey({
                keyId: keyId,
                expirationTime: formattedDate
            });

            if (res.code === 200) {
                Toast.show({
                    type: 'success',
                    text1: '更新成功',
                });
                await fetchKeyInfo();
            } else {
                Toast.show({
                    type: 'error',
                    text1: res.msg || '更新失败',
                });
            }
        } catch (error) {
            console.error('更新钥匙有效期错误:', error);
            Toast.show({
                type: 'error',
                text1: '更新失败',
            });
        } finally {
            setIsLoading(false);
            setShowTimeModal(false);
        }
    };

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

    const calculateRemainingTime = (expirationTime: string): string => {
        const now = new Date();
        const expiration = new Date(expirationTime);
        const diffTime = expiration.getTime() - now.getTime();

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

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

        if (days > 0) return `${days}天${hours}小时`;
        if (hours > 0) return `${hours}小时${minutes}分钟`;
        return `${minutes}分钟`;
    };

    const RightIcon = (props: any) => (
        <Image
            source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uGq4yJlU1ZZRkwiJ8Y74' }}
            style={styles.arrowIcon}
        />
    );

    const toQrCode = () => {
        navigation.navigate('ShareQrcode', { QrId: keyId });
    };


    return (
        <Layout style={styles.container}>
            <TopNavigation
                title="共享详情"
                alignment="center"
                accessoryLeft={BackAction}
                style={styles.topNav}
            />


            {keyItem && (  // 添加条件渲染检查
                <>
                    <Layout style={styles.header}>
                        <Avatar
                            style={styles.avatar}
                            size="giant"
                            source={{ uri: keyItem.avatarUrl || 'https://lxnapi.ccttiot.com/bike/img/static/uVnIDwcwQP7oo12PeYVJ' }}
                        />
                        <Text style={styles.name}>{keyItem.shareUserName}</Text>
                        <Text style={styles.phone}>{keyItem.sharePhone}</Text>
                        <Text style={styles.expireTime}>剩余有效期：{calculateRemainingTime(keyItem.expirationTime)}</Text>
                        <TouchableOpacity style={styles.eidtBtn} onPress={() => setShowTimeModal(true)}>
                            <View style={styles.editBtnContent}>
                                <Text style={styles.editBtnText}>修改钥匙有效期</Text>
                                <Icon name='arrow-ios-forward-outline' style={styles.arrowIcon} />
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.deleteBtn} onPress={showDeleteModal}>
                            <Text style={styles.deleteText}>删除共享人</Text>
                        </TouchableOpacity>
                    </Layout>

                    <Layout style={styles.actionContainer}>
                        <Button
                            appearance='ghost'
                            style={styles.actionButton}
                            accessoryRight={RightIcon}
                            onPress={toQrCode}
                        >
                            {evaProps => <Text {...evaProps} style={styles.buttonText}>查看二维码</Text>}
                        </Button>
                    </Layout>
                </>
            )}

            {/* 删除确认弹窗 */}
            <Modal
                visible={visible}
                transparent={true}
                animationType="fade"
                onRequestClose={hideDeleteModal}>
                <View style={styles.modalOverlay}>
                    <View style={styles.modalCard}>
                        <Text style={styles.modalText}>删除后，被共享人将无法再操控 您的车辆，确定删除吗？</Text>
                        <View style={styles.modalButtons}>
                            <Button
                                style={styles.modalButton}
                                status='basic'
                                size='large'
                                onPress={hideDeleteModal}>
                                取消
                            </Button>
                            <Button
                                style={styles.modalButton}
                                status='danger'
                                size='large'
                                onPress={handleDelete}>
                                删除
                            </Button>
                        </View>
                    </View>
                </View>
            </Modal>

            {/* 时间选择弹窗 */}
            <Modal
                visible={showTimeModal}
                transparent={true}
                animationType="slide"
                onRequestClose={() => setShowTimeModal(false)}>
                <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,
                                        selectedTime === option && styles.selectedItemBg
                                    ]}
                                    onPress={() => handleTimeSelect(option)}
                                >
                                    <Text style={[
                                        styles.optionText,
                                        selectedTime === option && styles.selectedOption
                                    ]}>
                                        {option}
                                    </Text>
                                </TouchableOpacity>
                            ))}
                        </View>
                    </View>
                </View>
            </Modal>
        </Layout>
    );
};

const styles = StyleSheet.create({
    container: {
        width: rpx(750),
        flex: 1,
        backgroundColor: '#F3FCFF',
    },
    topNav: {
        backgroundColor: '#F3FCFF',
        borderBottomWidth: 1,
        borderBottomColor: '#fff',
    },
    header: {
        marginHorizontal: 'auto',
        width: rpx(700),
        alignItems: 'center',
        backgroundColor: '#fff',
        paddingVertical: rpx(40),
        marginTop: rpx(20),
        alignSelf: 'center',
        borderRadius: rpx(16),
    },
    avatar: {
        width: rpx(188),
        height: rpx(188),
        marginBottom: rpx(16),
    },
    name: {
        fontWeight: 'bold',
        fontSize: rpx(48),
        color: '#333',
        marginBottom: rpx(8),
    },
    deleteBtn: {
        marginTop: rpx(56),
    },
    deleteText: {
        fontWeight: 'bold',
        fontSize: rpx(40),
        color: '#FF8282',
    },
    eidtBtn: {
        width: rpx(592),
        marginTop: rpx(20),
        height: rpx(108),
        backgroundColor: '#EEEFF9',
        borderRadius: rpx(16),
    },
    editBtnContent: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: rpx(16),
    },
    editBtnText: {
        fontSize: rpx(36),
        color: '#808080',
    },
    phone: {
        fontSize: rpx(36),
        color: '#808080',
        marginBottom: rpx(8),
    },
    expireTime: {
        marginTop: rpx(20),
        fontWeight: '400',
        fontSize: rpx(36),
        color: '#808080',
    },
    actionContainer: {
        marginHorizontal: 'auto',
        width: rpx(700),
        backgroundColor: '#fff',
        marginTop: rpx(20),
    },
    actionButton: {
        justifyContent: 'space-between',
        paddingHorizontal: rpx(32),
        paddingVertical: rpx(24),
        backgroundColor: '#fff',
        borderRadius: 0,
    },
    buttonText: {
        fontSize: rpx(36),
        color: '#3D3D3D',
    },
    arrowIcon: {
        width: rpx(38),
        height: rpx(38),
        tintColor: '#999',
    },
    deleteButton: {
        paddingVertical: rpx(24),
        backgroundColor: '#fff',
        borderRadius: 0,
    },
    divider: {
        backgroundColor: '#E8E8E8',
    },
    modalOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    modalCard: {
        width: rpx(600),
        borderRadius: rpx(20),
        padding: rpx(32),
        backgroundColor: '#fff',
    },
    modalText: {
        textAlign: 'center',
        marginBottom: rpx(40),
        fontSize: rpx(36),
        fontWeight: '500',
        color: '#333',
    },
    modalButtons: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginTop: rpx(20),
    },
    modalButton: {
        flex: 1,
        marginHorizontal: rpx(15),
        borderRadius: rpx(16),
        height: rpx(88),
    },
    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(600),
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: rpx(16),
        marginBottom: rpx(20),
    },
    optionText: {
        fontSize: rpx(32),
        color: '#333',
    },
    selectedItemBg: {
        backgroundColor: '#F0F7FF',
    },
    selectedOption: {
        color: '#4297F3',
    },
});

export default KeyDetail;