import React, { useState, useEffect, useRef } from 'react';
import { View, StyleSheet, Image, ImageBackground, TouchableOpacity, Text, Platform, NativeModules } from 'react-native';
import { rpx } from '../../utils/rpx';
import { RouteProp, useRoute } from '@react-navigation/native';
import RNFS from 'react-native-fs';
import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import { Spinner, Layout } from '@ui-kitten/components';
import QRCode from 'react-native-qrcode-svg';
import { captureRef } from 'react-native-view-shot';
import Toast from 'react-native-toast-message';

const ShareQrcode = () => {
    const route = useRoute<RouteProp<RootStackParamList, 'ShareQrcode'>>();
    const { QrId } = route.params;
    const [loading, setLoading] = useState(true);
    const qrCodeUrl = `https://testlu.chuangtewl.com/prod-api?keyId=${QrId}`;
    const logoUrl = 'https://lxnapi.ccttiot.com/bike/img/static/u3giTY4VkWYpnGWRuFHF';
    const qrRef = useRef();
    
    useEffect(() => {
        const timer = setTimeout(() => {
            setLoading(false);
        }, 1000);

        return () => clearTimeout(timer);
    }, []);

    const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
        Toast.show({
            type,
            text1: message,
            position: 'top',
            topOffset: Platform.OS === 'ios' ? 60 : 20,
            visibilityTime: 2000,
        });
    };

    const saveToGallery = async () => {
        try {
            const writePermission = await request(
                Platform.select({
                    android: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
                    default: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
                })
            );
    
            if (writePermission !== RESULTS.GRANTED) {
                showToast('请在设置中授予存储权限', 'error');
                return;
            }
    
            const fileName = `qrcode_${Date.now()}.jpg`;
            const tempPath = `${RNFS.CachesDirectoryPath}/${fileName}`;
    
            const uri = await captureRef(qrRef, {
                format: 'jpg',
                quality: 1,
                result: 'base64',
            });
    
            await RNFS.writeFile(tempPath, uri, 'base64');
    
            await Promise.race([
                new Promise((resolve, reject) => {
                    NativeModules.MediaScanner.scanFile(
                        tempPath,
                        'image/jpeg',
                        (error) => {
                            if (error) {
                                console.warn('MediaScanner warning:', error);
                                resolve(true);
                            } else {
                                resolve(true);
                            }
                        }
                    );
                }),
                new Promise((resolve) => setTimeout(resolve, 3000))
            ]);
    
            showToast('二维码已保存到相册', 'success');
    
            RNFS.unlink(tempPath).catch(e => {
                console.warn('清理临时文件失败:', e);
            });
    
        } catch (error) {
            console.error('Save error:', error);
            showToast('文件可能已保存到相册，请检查', 'info');
        }
    };

    if (loading) {
        return (
            <Layout style={styles.loadingContainer}>
                <Spinner size='giant' />
                <Text style={styles.loadingText}>二维码生成中...</Text>
            </Layout>
        );
    }

    return (
        <View style={styles.container}>
            <Image 
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uvDKCdnlkcshHOrXvPUq' }} 
                style={styles.backimg} 
            />
            <ImageBackground
                source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/u8yqVl9y6fcU3fTDDTpK' }}
                style={styles.qrBack}
            >
                <Layout style={styles.qrContainer} ref={qrRef}>
                    <QRCode
                        value={qrCodeUrl}
                        size={rpx(438)}
                        color="black"
                        backgroundColor="white"
                        logo={{ uri: logoUrl }}
                        logoSize={rpx(88)}
                        logoBackgroundColor='white'
                        logoBorderRadius={rpx(10)}
                    />
                </Layout>
            </ImageBackground>      
            <Image source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uC6GRh4c76KgsbBYME5l' }} style={styles.tipImg} />
            <TouchableOpacity style={styles.btn} onPress={saveToGallery}>
                <Text style={styles.btnText}>保存至图片</Text>
            </TouchableOpacity>
            <Toast />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#F3FCFF',
    },
    loadingContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadingText: {
        marginTop: 10,
        fontSize: 16,
        color: '#888',
    },
    btn: {
        marginTop: rpx(36),
        width: rpx(614),
        height: rpx(92),
        backgroundColor: '#3D3D3D',
        borderRadius: rpx(16),
        alignItems: 'center',
        justifyContent: 'center', 
    },
    btnText: {
        color: '#fff',
        fontSize: rpx(40),
        fontWeight: 'bold',
    },
    tipImg: {
        marginTop: rpx(26),
        width: rpx(614),
        height: rpx(368),
    },
    qrContainer: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'white',
        padding: rpx(20),
        borderRadius: rpx(10),
    },
    qrBack: {
        marginTop: rpx(-20),
        width: rpx(614),
        height: rpx(614),
        padding: rpx(86),
        alignItems: 'center',
        justifyContent: 'center',
    },
    backimg: {
        width: rpx(688),
        height: rpx(236),
    }
});

export default ShareQrcode;