import { Images } from '@/constants/images';
import { getParamConfig } from '@/services/user';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { Dimensions, ImageBackground, Modal, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

export interface WishRuleModalRef {
    show: () => void;
    close: () => void;
}

// 简单的HTML标签清理函数
const stripHtmlTags = (html: string): string => {
    if (!html) return '';
    return html
        .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
        .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
        .replace(/<[^>]+>/g, '\n')
        .replace(/&nbsp;/g, ' ')
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&')
        .replace(/\n\s*\n/g, '\n\n') // Merge multiple newlines
        .trim();
};

export const WishRuleModal = forwardRef<WishRuleModalRef, {}>((props, ref) => {
    const [visible, setVisible] = useState(false);
    const [content, setContent] = useState('');

    useImperativeHandle(ref, () => ({
        show: () => {
            setVisible(true);
            loadRule();
        },
        close: () => setVisible(false),
    }));

    const loadRule = async () => {
        try {
            const res = await getParamConfig('wish_rule');
            if (res && res.data) {
                setContent(stripHtmlTags(res.data));
            }
        } catch (error) {
            console.error('加载祈愿规则失败:', error);
        }
    };

    if (!visible) return null;

    return (
        <Modal visible={visible} transparent animationType="fade" onRequestClose={() => setVisible(false)}>
            <View style={styles.overlay}>
                <View style={styles.windowSection}>
                    <ImageBackground style={styles.main} source={{ uri: Images.common.windBg }} resizeMode="stretch">
                        <ScrollView 
                            style={styles.scrollView}
                            contentContainerStyle={styles.scrollContent}
                            showsVerticalScrollIndicator={false}
                        >
                            <Text style={styles.text}>{content || '暂无规则内容'}</Text>
                            <Text style={[styles.text, { marginTop: 15, color: '#999', fontSize: 12 }]}>特别声明：本祈愿福利活动由艾斯潮盒官方发起，与苹果公司（Apple Inc.）无关。苹果公司不是活动的赞助商，也没有以任何形式参与。</Text>
                        </ScrollView>
                    </ImageBackground>

                    {/* 关闭按钮 - 移到底部 */}
                    <TouchableOpacity style={styles.closeBtn} onPress={() => setVisible(false)}>
                        <ImageBackground source={{ uri: Images.common.closeBut }} style={styles.closeIcon} resizeMode="contain" />
                    </TouchableOpacity>
                </View>
            </View>
        </Modal>
    );
});

export default WishRuleModal;

const styles = StyleSheet.create({
    overlay: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.7)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    windowSection: {
        width: SCREEN_WIDTH,
        alignItems: 'center',
    },
    main: {
        width: 360, // 720rpx
        height: 302, // 604rpx
        paddingTop: 90, // 180rpx
        paddingHorizontal: 30, // 60rpx
        alignItems: 'center',
        zIndex: 1,
        marginBottom: 20, // Space between modal and close button
    },
    scrollView: {
        width: '100%',
        height: 190, // 380rpx
    },
    scrollContent: {
        paddingBottom: 20,
    },
    text: {
        fontSize: 14,
        color: '#8B4513',
        lineHeight: 22,
    },
    closeBtn: {
        width: 35,
        height: 35,
    },
    closeIcon: {
        width: '100%',
        height: '100%',
    },
});
