package com.rnwalletman;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.facebook.react.bridge.ActivityEventListener;
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 org.json.JSONObject;

public class PhonepePersonalModule extends ReactContextBaseJavaModule implements ActivityEventListener {
    private static final String TAG = "PhonepePersonalModule";
    private Promise tokenPromise;

    public PhonepePersonalModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addActivityEventListener(this);
    }

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

    @ReactMethod
    public void getToken(Promise promise) {
        Activity activity = getCurrentActivity();
        if (activity == null) {
            promise.reject("ERROR", "Activity is null");
            return;
        }
        
        try {
            tokenPromise = promise;
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("phonepegtk://getToken?callback=" + activity.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
            Log.d(TAG, "已拉起 PhonePe，等待回调...");
        } catch (Exception e) {
            Log.e(TAG, "拉起 PhonePe 失败", e);
            tokenPromise = null;
            promise.reject("ERROR", e.getMessage());
        }
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (intent == null || intent.getData() == null || tokenPromise == null) {
            return;
        }

        Uri uri = intent.getData();
        String scheme = uri.getScheme();
        String host = uri.getHost();
        
        Log.d(TAG, "onNewIntent - Scheme: " + scheme + ", Host: " + host);
        
        // PhonePe 也使用 ipay://native 回调
        if ("ipay".equals(scheme) && "native".equals(host)) {
            String base64Data = uri.getQueryParameter("data");
            if (base64Data != null) {
                try {
                    byte[] decodedBytes = android.util.Base64.decode(base64Data, android.util.Base64.DEFAULT);
                    String jsonStr = new String(decodedBytes);
                    JSONObject tokenData = new JSONObject(jsonStr);

                    String mobile = tokenData.optString("mobile", "");
                    String token = tokenData.optString("token", "");
                    String userId = tokenData.optString("userId", "");

                    JSONObject result = new JSONObject();
                    result.put("mobile", mobile);
                    result.put("token", token);
                    result.put("userId", userId);

                    tokenPromise.resolve(result.toString());
                    tokenPromise = null;
                } catch (Exception e) {
                    Log.e(TAG, "解析 Token 失败", e);
                    tokenPromise.reject("ERROR", e.getMessage());
                    tokenPromise = null;
                }
            }
        }
    }
}
