import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import {
    Dimensions,
    ImageBackground,
    Modal,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
} from 'react-native';

import { Images } from '@/constants/images';
import { getParamConfig } from '@/services/user';

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

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

export const RuleModal = forwardRef<RuleModalRef>((_, ref) => {
  const [visible, setVisible] = useState(false);
  const [rules, setRules] = useState('');

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

  const loadRules = async () => {
    try {
      const res = await getParamConfig('baoxiang_rule');
      // 增强清洗：移除 style/script，去除 HTML 标签，并压缩多余空行
      const rawData = res?.data || '';
      const text = rawData
        .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
        .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
        .replace(/<[^>]+>/g, '')
        .replace(/&nbsp;/g, ' ')
        .replace(/\n\s*\n/g, '\n') // 将多个空行压缩为一个
        .trim() || '平台发货零门槛，全国统一运费15元/单，满五件享快递包邮服务，默认5个工作日内完成发货。';
      setRules(text);
    } catch (error) {
      console.error('加载规则失败:', error);
      setRules('平台发货零门槛，全国统一运费15元/单，满五件享快递包邮服务，默认5个工作日内完成发货。');
    }
  };

  useEffect(() => {
    if (visible && !rules) loadRules();
  }, [visible]);

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={() => setVisible(false)}>
      <View style={styles.overlay}>
        <View style={styles.container}>
          {/* 内容区域 */}
          <ImageBackground
            source={{ uri: Images.mine.dialogContentBg }}
            style={styles.contentBg}
            resizeMode="stretch"
          >
            <Text style={styles.title}>玩法规则</Text>
            <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
              <Text style={styles.ruleText}>{rules}</Text>
              <Text style={[styles.ruleText, { marginTop: 15, color: '#999', fontSize: 12 }]}>特别声明：本抽赏活动及相关福利均由艾斯潮盒官方发起，与苹果公司（Apple Inc.）无关。苹果公司不是活动的赞助商，也没有以任何形式参与。</Text>
            </ScrollView>
          </ImageBackground>

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

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  container: {
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
  contentBg: {
    width: SCREEN_WIDTH * 0.85,
    height: SCREEN_WIDTH * 0.85 * 1.25,
    paddingTop: 85,
    paddingHorizontal: 35,
    paddingBottom: 50,
    justifyContent: 'flex-start',
    marginBottom: 30, // 给下方按钮留出空间
  },
  closeBtn: {
    width: 45,
    height: 45,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 10,
  },
  closeIcon: {
    width: '100%',
    height: '100%',
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
    marginBottom: 15,
  },
  scrollView: {
    flex: 1,
  },
  ruleText: {
    fontSize: 14,
    color: '#333',
    lineHeight: 20, // 降低行间距
  },
});
