import React, { useEffect, useState } from 'react';
import { View, StyleSheet, ActivityIndicator } from 'react-native';
import { WebView } from 'react-native-webview';
import { TopNavigation, TopNavigationAction, Icon, IconElement } from '@ui-kitten/components';
import { useRoute, useNavigation } from '@react-navigation/native';
import { apiService } from '../../utils/api';
import { rpx } from '../../utils/rpx';

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

const XmlRenderPage = () => {
    const navigation = useNavigation();
    const route = useRoute();
    const [xmlContent, setXmlContent] = useState('');
    const [title, setTitle] = useState('详情');
    const [loading, setLoading] = useState(true);
    const { id } = route.params;

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

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

    const replaceImgWithImage = (content) => {
        // 替换所有的&nbsp;为 \u00A0
        content = content.replace(/&nbsp;/g, '\u00A0');

        // 替换 <img> 标签的宽度和高度样式
        content = content.replace(/<img([^>]*)>/g, (match, group1) => {
            // 查找并移除可能存在的尾部斜杠
            let cleanedGroup = group1.replace(/\s*\/$/, '');
            return `<img style="width: 85vw; height: auto;" ${cleanedGroup} />`;
        });

        return content;
    };

    const fetchArticleById = async () => {
        console.log(id, 'id');
        const response = await apiService.getArticleById(id);
        console.log(response, '1111111111111');
        const modifiedContent = replaceImgWithImage(response.data.content);
        setXmlContent(modifiedContent);
        setTitle(response.data.title || '详情');
        setLoading(false);
    }

    useEffect(() => {
        fetchArticleById();
    }, []);

    return (
        <View style={styles.container}>
            <TopNavigation
                title={title}
                alignment='center'
                accessoryLeft={BackAction}
                style={styles.header}
            />
            {loading ? (
                <ActivityIndicator size="large" color="#0000ff" style={styles.loading} />
            ) : (
                <WebView
                    originWhitelist={['*']}
                    source={{ html: xmlContent }}
                    style={styles.webview}
                    scalesPageToFit={false}
                    injectedJavaScript={`
                        const meta = document.createElement('meta');
                        meta.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1');
                        meta.setAttribute('name', 'viewport');
                        document.getElementsByTagName('head')[0].appendChild(meta);
                    `}
                />
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        backgroundColor: 'transparent',
        elevation: 0,
        shadowOpacity: 0,
    },
    webview: {
        width: rpx(750),
        flex: 1,
    },
    loading: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
});

export default XmlRenderPage;