import React, { useEffect, useState } from 'react';
import { View, StyleSheet, ActivityIndicator, Text, TouchableOpacity } 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 FranchisePage = () => {
    const navigation = useNavigation();
    const route = useRoute();
    const [xmlContent, setXmlContent] = useState('');
    const [title, setTitle] = useState('详情');
    const [loading, setLoading] = useState(true);
    const [isAgreed, setIsAgreed] = useState(false);

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

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

    const replaceImgWithImage = (content) => {
        content = content.replace(/&nbsp;/g, '\u00A0');
        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 () => {
        const response = await apiService.getArticleById(29);
        console.log(response, '1111111111111');
        const modifiedContent = replaceImgWithImage(response.data.content);
        setXmlContent(modifiedContent);
        setTitle(response.data.title || '详情');
        setLoading(false);
    }

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

    const handleApply = () => {
        if (isAgreed) {
            console.log('申请成为商家');
        } else {
            alert('请先同意协议');
        }
    };

    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 style={styles.footer}>
                <TouchableOpacity
                    style={styles.agreementContainer}
                    onPress={() => setIsAgreed(!isAgreed)}
                >
                    <View style={styles.checkbox}>
                        {isAgreed && <Text style={styles.checkmark}>✓</Text>}
                    </View>
                    <Text style={styles.agreementText}>同意《{title}》</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.applyButton}
                    onPress={handleApply}
                >
                    <Text style={styles.applyButtonText}>申请成为商家</Text>
                </TouchableOpacity>
            </View>
        </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',
    },
    footer: {
        padding: rpx(20),
        borderTopWidth: 1,
        borderColor: '#ccc',
        backgroundColor: '#fff',
        alignItems: 'center',
    },
    agreementContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: rpx(10),
    },
    checkbox: {
        width: rpx(24),
        height: rpx(24),
        borderWidth: 1,
        borderColor: '#000',
        justifyContent: 'center',
        alignItems: 'center',
        marginRight: rpx(8),
    },
    checkmark: {
        fontSize: rpx(18),
        color: '#000',
    },
    agreementText: {
        fontSize: rpx(24),
        color: '#000',
    },
    applyButton: {
        marginTop: rpx(20),
        marginBottom: rpx(20),
        backgroundColor: '#007bff',
        paddingVertical: rpx(26),
        paddingHorizontal: rpx(30),
        borderRadius: rpx(15),
        width: '85%',
        alignItems: 'center',
    },
    applyButtonText: {
        color: '#fff',
        fontSize: rpx(32),
    },
});

export default FranchisePage;