package com.rnwalletman;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
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 net.one97.paytm.upi.transaction.common.models.o;

import org.json.JSONObject;

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

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

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

    @ReactMethod
    public void getToken(Promise promise) {
        try {
            tokenPromise = promise;
            Activity activity = getCurrentActivity();
            if (activity == null) {
                promise.reject("ERROR", "Activity is null");
                return;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("paytmgtk://getToken"));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "拉起 Paytm 失败", e);
            promise.reject("ERROR", e.getMessage());
            tokenPromise = null;
        }
    }

    @ReactMethod
    @SuppressLint("WrongConstant")
    public void pay(String amount, String payeeName, String accountNo, String ifscCode, String comments, Promise promise) {
        try {
            Activity activity = getCurrentActivity();
            if (activity == null) {
                promise.reject("ERROR", "Activity is null");
                return;
            }
            
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(
                    "net.one97.paytm",
                    "net.one97.paytm.moneytransfer.eas.view.activity.MTEnterAmountActivity"
            ));

            Bundle bundle = new Bundle();
            bundle.putString("payee_name", payeeName);
            bundle.putString("account_no", accountNo);
            bundle.putString("bankname", ifscCode.substring(0, 4));
            bundle.putString("ifsc", ifscCode);
            bundle.putString("amount", amount);
            bundle.putString("comments", comments);
            bundle.putBoolean("post_txn_scan_flow", false);
            bundle.putBoolean("post_txn_collect_flow", false);

            intent.putExtra("post_txn_data", bundle);
            intent.putExtra("t", o.INSTANCE);
            intent.addFlags(268468224);

            activity.startActivity(intent);
            promise.resolve(true);
        } catch (Exception e) {
            Log.e(TAG, "Paytm 支付失败", e);
            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();
        if ("ipay".equals(uri.getScheme()) && "native".equals(uri.getHost())) {
            String base64Data = uri.getQueryParameter("data");
            if (base64Data != null) {
                try {
                    byte[] decodedBytes = Base64.decode(base64Data, 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) {
                    tokenPromise.reject("ERROR", e.getMessage());
                    tokenPromise = null;
                }
            }
        }
    }
}
