package com.hs.sosnow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class SosHelper {

    private final Context context;
    private final SharedPreferences prefs;
    private final Gson gson = new Gson();
    private final FusedLocationProviderClient locationClient;
    private final TelecomManager telecomManager;
    private final TelephonyManager telephonyManager;

    private static final List<String> callSequence = new ArrayList<>();
    private static int currentCallIndex = 0;
    private static boolean callActive = false;
    private static PhoneStateListener failoverListener = null;

    public SosHelper(Context context) {
        this.context = context;
        this.prefs = context.getSharedPreferences("SosNowPrefs", Context.MODE_PRIVATE);
        this.locationClient = LocationServices.getFusedLocationProviderClient(context);
        this.telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
        this.telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    }

    @SuppressLint("MissingPermission")
    public void executeEmergency() {
        List<String> callList = getList("CALL_CONTACTS");
        String priorityPhone = prefs.getString("PRIORITY_CALL_PHONE", "");

        if (callList.isEmpty()) {
            Toast.makeText(context, "Kripya Settings me contact add karein!", Toast.LENGTH_SHORT).show();
            return;
        }

        callSequence.clear();
        if (!priorityPhone.isEmpty()) {
            callSequence.add(priorityPhone);
        }
        for (String ph : callList) {
            if (!callSequence.contains(ph)) {
                callSequence.add(ph);
            }
        }
        currentCallIndex = 0;

        List<String> smsRecipients = getList("SMS_CONTACTS");
        if (smsRecipients.isEmpty()) {
            smsRecipients.addAll(callSequence);
        }

        List<String> finalSmsList = smsRecipients;

        locationClient.getLastLocation().addOnSuccessListener(loc -> {
            double lat = loc != null ? loc.getLatitude() : 0.0;
            double lng = loc != null ? loc.getLongitude() : 0.0;
            String mapUrl = "https://maps.google.com/?q=" + lat + "," + lng;

            // 1. Direct Cellular SMS
            dispatchDirectSms(finalSmsList, "EMERGENCY! Mujhe turant sahayata chahiye. Live GPS: " + mapUrl);

            // 2. Setup call cascade listener
            registerSmartFailover();

            // 3. Dial without SIM chooser dialog
            dialWithoutSimPrompt();

            // 4. Cloud incident alert
            triggerCloudBroadcast(lat, lng);
        });
    }

    @SuppressLint("MissingPermission")
    private void dispatchDirectSms(List<String> list, String text) {
        try {
            SubscriptionManager sm = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
            List<SubscriptionInfo> subs = (sm != null) ? sm.getActiveSubscriptionInfoList() : null;

            SmsManager smsMgr;
            if (subs != null && !subs.isEmpty()) {
                int id = subs.get(0).getSubscriptionId();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    smsMgr = context.getSystemService(SmsManager.class).createForSubscriptionId(id);
                } else {
                    smsMgr = SmsManager.getSmsManagerForSubscriptionId(id);
                }
            } else {
                smsMgr = SmsManager.getDefault();
            }

            for (String num : list) {
                smsMgr.sendTextMessage(num, null, text, null, null);
            }
        } catch (Exception e) {
            try {
                SmsManager fallback = SmsManager.getDefault();
                for (String num : list) {
                    fallback.sendTextMessage(num, null, text, null, null);
                }
            } catch (Exception ignored) {}
        }
    }

    @SuppressLint("MissingPermission")
    private void dialWithoutSimPrompt() {
        if (currentCallIndex >= callSequence.size()) return;

        String phone = callSequence.get(currentCallIndex);
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Hardware Phone Account Bind to bypass System SIM Selection Popup
        if (telecomManager != null) {
            PhoneAccountHandle targetHandle = null;
            try {
                targetHandle = telecomManager.getDefaultOutgoingPhoneAccount("tel");
            } catch (Exception ignored) {}

            if (targetHandle == null) {
                List<PhoneAccountHandle> handles = telecomManager.getCallCapablePhoneAccounts();
                if (handles != null && !handles.isEmpty()) {
                    targetHandle = handles.get(0);
                }
            }

            if (targetHandle != null) {
                intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, targetHandle);
            }
        }

        context.startActivity(intent);
    }

    private void registerSmartFailover() {
        if (failoverListener != null) return;

        failoverListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String phoneNumber) {
                super.onCallStateChanged(state, phoneNumber);
                switch (state) {
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        callActive = true;
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        if (callActive) {
                            callActive = false;
                            currentCallIndex++;
                            if (currentCallIndex < callSequence.size()) {
                                new android.os.Handler(android.os.Looper.getMainLooper())
                                        .postDelayed(SosHelper.this::dialWithoutSimPrompt, 800);
                            }
                        }
                        break;
                }
            }
        };
        telephonyManager.listen(failoverListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    private void triggerCloudBroadcast(double lat, double lng) {
        new Thread(() -> {
            String token = prefs.getString("AUTH_TOKEN", "");
            if (token.isEmpty()) return;

            try {
                URL url = new URL(AppConfig.SERVER_BASE_URL + "?action=trigger_emergency");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setRequestProperty("Authorization", token);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                String post = "latitude=" + lat + "&longitude=" + lng;
                OutputStream os = conn.getOutputStream();
                os.write(post.getBytes());
                os.flush();

                BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String l;
                while ((l = r.readLine()) != null) sb.append(l);
                r.close();

                JSONObject res = new JSONObject(sb.toString());
                String incToken = res.optString("incident_token", "active");

                Intent sIntent = new Intent(context, SmartEvidenceService.class);
                sIntent.putExtra("INCIDENT_TOKEN", incToken);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(sIntent);
                } else {
                    context.startService(sIntent);
                }
            } catch (Exception ignored) {}
        }).start();
    }

    private List<String> getList(String key) {
        String json = prefs.getString(key, null);
        if (json != null) {
            Type type = new TypeToken<ArrayList<String>>() {}.getType();
            return gson.fromJson(json, type);
        }
        return new ArrayList<>();
    }
}