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

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

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

export const RuleModal = forwardRef<RuleModalRef, {}>((props, ref) => {
  const [visible, setVisible] = useState(false);
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);

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

  const loadRule = async (key: string) => {
    setLoading(true);
    try {
      const res = await getParamConfig(key);
      if (res && res.data) {
        // Simple HTML wrap
        const html = `
          <html>
            <head>
              <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
              <style>
                body { font-size: 14px; color: #333; padding: 10px; word-wrap: break-word; }
                img { max-width: 100%; height: auto; }
                p { margin: 5px 0; }
              </style>
            </head>
            <body>${res.data}</body>
          </html>
        `;
        setContent(html);
      }
    } catch (e) {
      console.error(e);
      setContent('<p>加载失败</p>');
    } finally {
      setLoading(false);
    }
  };

  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.bg}
                resizeMode="stretch"
             >
                 <View style={styles.content}>
                     {loading ? (
                         <ActivityIndicator color="#000" style={{ marginTop: 50 }} />
                     ) : (
                         <WebView 
                            originWhitelist={['*']}
                            source={{ html: content }}
                            style={styles.webview}
                            showsVerticalScrollIndicator={false}
                         />
                     )}
                 </View>
             </ImageBackground>

             {/* Close Button Moved to Bottom */}
             <TouchableOpacity style={styles.closeBtn} onPress={() => setVisible(false)}>
                  <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: width * 0.9,
    alignItems: 'center',
  },
  bg: {
      width: '100%',
      height: 400, // Adjust height
      paddingTop: 60,
      paddingHorizontal: 30,
      paddingBottom: 30,
      marginBottom: 30, // Space for button
  },
  content: {
      flex: 1,
      overflow: 'hidden',
  },
  webview: {
      flex: 1,
      backgroundColor: 'transparent',
  },
  closeBtn: {
      width: 45,
      height: 45,
      justifyContent: 'center',
      alignItems: 'center',
      zIndex: 10,
  },
  closeIcon: {
      width: '100%',
      height: '100%',
  }
});
