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

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

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('show_rule');
      // 去除HTML标签
      const text = res?.data?.replace(/<[^>]+>/g, '') || '平台发货零门槛，全国统一运费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}>
          {/* 关闭按钮 */}
          <TouchableOpacity onPress={() => setVisible(false)} style={styles.closeBtn}>
            <Image source={{ uri: Images.common.closeBut }} style={styles.closeIcon} contentFit="contain" />
          </TouchableOpacity>

          {/* 内容区域 */}
          <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>
            </ScrollView>
          </ImageBackground>
        </View>
      </View>
    </Modal>
  );
});

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  container: {
    width: '90%',
    alignItems: 'center',
  },
  closeBtn: {
    position: 'absolute',
    right: 15,
    top: 20,
    zIndex: 10,
    width: 35,
    height: 35,
  },
  closeIcon: {
    width: 35,
    height: 35,
  },
  contentBg: {
    width: '100%',
    height: 400,
    paddingTop: 75,
    paddingHorizontal: 30,
    paddingBottom: 30,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    textAlign: 'center',
    marginBottom: 15,
  },
  scrollView: {
    flex: 1,
  },
  ruleText: {
    fontSize: 14,
    color: '#666',
    lineHeight: 24,
  },
});
