package com.rnwalletman;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.provider.Telephony;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;

/**
 * SMS 和通知监听模块
 */
public class SmsNotificationModule extends ReactContextBaseJavaModule {
    private static final String TAG = "SmsNotificationModule";
    private static ReactApplicationContext reactContext;
    
    private static final String EVENT_SMS_RECEIVED = "onSmsMessage";
    private static final String EVENT_NOTIFICATION_RECEIVED = "onNotificationMessage";

    public SmsNotificationModule(ReactApplicationContext context) {
        super(context);
        reactContext = context;
    }

    @NonNull
    @Override
    public String getName() {
        return "SmsNotificationModule";
    }

    @ReactMethod
    public void addListener(String eventName) {
        // Set up any upstream listeners or background tasks as necessary
    }

    @ReactMethod
    public void removeListeners(Integer count) {
        // Remove upstream listeners, stop unnecessary background tasks
    }
    
    /**
     * 发送短信事件到 JS
     */
    public static void sendSmsEvent(String sender, String message, long timestamp) {
        if (reactContext == null) return;
        
        try {
            WritableMap params = Arguments.createMap();
            params.putString("address", sender);
            params.putString("body", message);
            params.putDouble("timestamp", timestamp);
            
            reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(EVENT_SMS_RECEIVED, params);
        } catch (Exception e) {
            Log.e(TAG, "发送SMS事件失败", e);
        }
    }
    
    /**
     * 发送通知事件到 JS
     */
    public static void sendNotificationEvent(String id, String packageName, String tag, 
                                            long postTime, String title, String text, String bigText) {
        if (reactContext == null) return;
        
        try {
            WritableMap params = Arguments.createMap();
            params.putString("id", id);
            params.putString("packageName", packageName);
            params.putString("tag", tag);
            params.putDouble("postTime", postTime);
            params.putString("title", title);
            params.putString("text", text);
            params.putString("bigText", bigText);
            
            reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(EVENT_NOTIFICATION_RECEIVED, params);
        } catch (Exception e) {
            Log.e(TAG, "发送通知事件失败", e);
        }
    }
    
    /**
     * 检查 SMS 权限
     */
    @ReactMethod
    public void checkSmsPermission(Promise promise) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                boolean hasReadSms = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
                boolean hasReceiveSms = ContextCompat.checkSelfPermission(reactContext, Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
                promise.resolve(hasReadSms && hasReceiveSms);
            } else {
                promise.resolve(true);
            }
        } catch (Exception e) {
            promise.reject("CHECK_PERMISSION_ERROR", e.getMessage());
        }
    }
    
    /**
     * 请求 SMS 权限
     */
    @ReactMethod
    public void requestSmsPermission(final Promise promise) {
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                promise.resolve(true);
                return;
            }
            
            PermissionAwareActivity activity = (PermissionAwareActivity) reactContext.getCurrentActivity();
            if (activity == null) {
                promise.reject("NO_ACTIVITY", "Activity is null");
                return;
            }
            
            String[] permissions = new String[]{
                Manifest.permission.READ_SMS,
                Manifest.permission.RECEIVE_SMS
            };
            
            activity.requestPermissions(permissions, 1, new PermissionListener() {
                @Override
                public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
                    if (requestCode == 1) {
                        boolean allGranted = true;
                        for (int result : grantResults) {
                            if (result != PackageManager.PERMISSION_GRANTED) {
                                allGranted = false;
                                break;
                            }
                        }
                        promise.resolve(allGranted);
                        return true;
                    }
                    return false;
                }
            });
        } catch (Exception e) {
            promise.reject("REQUEST_PERMISSION_ERROR", e.getMessage());
        }
    }
    
    /**
     * 检查通知监听权限
     */
    @ReactMethod
    public void checkNotificationPermission(Promise promise) {
        try {
            String packageName = reactContext.getPackageName();
            String flat = Settings.Secure.getString(reactContext.getContentResolver(), "enabled_notification_listeners");
            
            if (flat != null && flat.contains(packageName)) {
                promise.resolve(true);
            } else {
                promise.resolve(false);
            }
        } catch (Exception e) {
            promise.reject("CHECK_NOTIFICATION_PERMISSION_ERROR", e.getMessage());
        }
    }
    
    /**
     * 打开通知监听设置页面
     */
    @ReactMethod
    public void openNotificationSettings(Promise promise) {
        try {
            Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            reactContext.startActivity(intent);
            promise.resolve(true);
        } catch (Exception e) {
            promise.reject("OPEN_SETTINGS_ERROR", e.getMessage());
        }
    }
    
    /**
     * 启动 SMS 监听
     */
    @ReactMethod
    public void startSmsListener(Promise promise) {
        try {
            SharedPreferences prefs = reactContext.getSharedPreferences("rnwalletman", ReactApplicationContext.MODE_PRIVATE);
            prefs.edit().putBoolean("sms_enabled", true).apply();
            Log.i(TAG, "SMS 监听已启用");
            promise.resolve(true);
        } catch (Exception e) {
            promise.reject("START_SMS_LISTENER_ERROR", e.getMessage());
        }
    }
    
    /**
     * 停止 SMS 监听
     */
    @ReactMethod
    public void stopSmsListener(Promise promise) {
        try {
            SharedPreferences prefs = reactContext.getSharedPreferences("rnwalletman", ReactApplicationContext.MODE_PRIVATE);
            prefs.edit().putBoolean("sms_enabled", false).apply();
            Log.i(TAG, "SMS 监听已停止");
            promise.resolve(true);
        } catch (Exception e) {
            promise.reject("STOP_SMS_LISTENER_ERROR", e.getMessage());
        }
    }
    
    /**
     * 启动通知监听
     */
    @ReactMethod
    public void startNotificationListener(Promise promise) {
        try {
            SharedPreferences prefs = reactContext.getSharedPreferences("rnwalletman", ReactApplicationContext.MODE_PRIVATE);
            prefs.edit().putBoolean("notification_enabled", true).apply();
            Log.i(TAG, "通知监听已启用");
            promise.resolve(true);
        } catch (Exception e) {
            promise.reject("START_NOTIFICATION_LISTENER_ERROR", e.getMessage());
        }
    }
    
    /**
     * 停止通知监听
     */
    @ReactMethod
    public void stopNotificationListener(Promise promise) {
        try {
            SharedPreferences prefs = reactContext.getSharedPreferences("rnwalletman", ReactApplicationContext.MODE_PRIVATE);
            prefs.edit().putBoolean("notification_enabled", false).apply();
            Log.i(TAG, "通知监听已停止");
            promise.resolve(true);
        } catch (Exception e) {
            promise.reject("STOP_NOTIFICATION_LISTENER_ERROR", e.getMessage());
        }
    }

    /**
     * 读取所有短信
     * @param limit 限制数量，0 表示全部
     */
    @ReactMethod
    public void getAllSms(int limit, Promise promise) {
        try {
            WritableArray result = Arguments.createArray();
            ContentResolver cr = reactContext.getContentResolver();
            
            Uri uri = Telephony.Sms.CONTENT_URI;
            String[] projection = new String[] {
                Telephony.Sms._ID,
                Telephony.Sms.ADDRESS,
                Telephony.Sms.BODY,
                Telephony.Sms.DATE,
                Telephony.Sms.TYPE,
                Telephony.Sms.READ
            };
            
            String sortOrder = Telephony.Sms.DATE + " DESC";
            if (limit > 0) {
                sortOrder += " LIMIT " + limit;
            }
            
            Cursor cursor = cr.query(uri, projection, null, null, sortOrder);
            
            if (cursor != null) {
                int count = 0;
                while (cursor.moveToNext() && (limit == 0 || count < limit)) {
                    WritableMap sms = Arguments.createMap();
                    
                    sms.putString("id", cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms._ID)));
                    sms.putString("address", cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)));
                    sms.putString("body", cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.BODY)));
                    sms.putDouble("timestamp", cursor.getLong(cursor.getColumnIndexOrThrow(Telephony.Sms.DATE)));
                    sms.putInt("type", cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Sms.TYPE)));
                    sms.putBoolean("read", cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Sms.READ)) == 1);
                    
                    result.pushMap(sms);
                    count++;
                }
                cursor.close();
            }
            
            Log.i(TAG, "读取短信: " + result.size() + " 条");
            promise.resolve(result);
        } catch (Exception e) {
            Log.e(TAG, "读取短信失败", e);
            promise.reject("SMS_READ_ERROR", e.getMessage());
        }
    }

    /**
     * 读取所有活跃通知
     * 需要先在系统设置中授权通知监听
     */
    @ReactMethod
    public void getAllNotifications(Promise promise) {
        try {
            RNWalletNotificationListener service = RNWalletNotificationListener.getInstance();
            
            Log.d(TAG, "获取通知监听服务实例: " + (service != null ? "成功" : "失败"));
            
            if (service == null) {
                // 服务未运行，返回空数组而非错误（可能系统还未启动服务）
                Log.w(TAG, "通知监听服务未运行，返回空数组");
                promise.resolve(Arguments.createArray());
                return;
            }
            
            StatusBarNotification[] notifications = service.readActiveNotifications();
            WritableArray result = Arguments.createArray();
            
            Log.d(TAG, "从系统获取到 " + notifications.length + " 条通知");
            
            for (StatusBarNotification sbn : notifications) {
                WritableMap notification = Arguments.createMap();
                
                notification.putString("id", String.valueOf(sbn.getId()));
                notification.putString("packageName", sbn.getPackageName());
                notification.putString("tag", sbn.getTag());
                notification.putDouble("postTime", sbn.getPostTime());
                
                if (sbn.getNotification() != null && sbn.getNotification().extras != null) {
                    notification.putString("title", getStringFromExtras(sbn.getNotification().extras, "android.title"));
                    notification.putString("text", getStringFromExtras(sbn.getNotification().extras, "android.text"));
                    notification.putString("bigText", getStringFromExtras(sbn.getNotification().extras, "android.bigText"));
                }
                
                result.pushMap(notification);
            }
            
            Log.i(TAG, "返回通知数据: " + result.size() + " 条");
            promise.resolve(result);
        } catch (Exception e) {
            Log.e(TAG, "读取通知失败", e);
            promise.reject("NOTIFICATION_READ_ERROR", e.getMessage());
        }
    }
    
    /**
     * 从 Bundle 中安全地获取字符串
     */
    private String getStringFromExtras(android.os.Bundle extras, String key) {
        if (extras == null || key == null) {
            return "";
        }
        
        Object obj = extras.get(key);
        if (obj == null) {
            return "";
        }
        
        return obj.toString();
    }
}
