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

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');
      setRules(res?.data || '暂无规则说明');
    } catch (error) {
      console.error('加载规则失败:', error);
    }
  };

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

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={() => setVisible(false)}>
      <View style={styles.overlay}>
        <View style={styles.container}>
          <View style={styles.header}>
            <Text style={styles.title}>玩法规则</Text>
            <TouchableOpacity onPress={() => setVisible(false)} style={styles.closeBtn}>
              <Text style={styles.closeText}>×</Text>
            </TouchableOpacity>
          </View>
          <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
            <Text style={styles.ruleText}>{rules}</Text>
          </ScrollView>
        </View>
      </View>
    </Modal>
  );
});


const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  container: {
    width: '85%',
    maxHeight: '70%',
    backgroundColor: '#fff',
    borderRadius: 15,
    overflow: 'hidden',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    backgroundColor: '#ff6600',
  },
  title: { fontSize: 16, fontWeight: '600', color: '#fff' },
  closeBtn: { position: 'absolute', right: 15, top: 10 },
  closeText: { fontSize: 24, color: '#fff' },
  content: { padding: 15 },
  ruleText: { fontSize: 14, color: '#333', lineHeight: 22 },
});
