package com.hs.sosnow;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class SettingsActivity extends AppCompatActivity {

    private EditText etCallInput, etSmsInput;
    private LinearLayout containerSavedCalls, containerSavedSms, containerHelplines;
    private NumberPicker pickerTimerSeconds;
    private TextView tvTimerLabel;

    private SharedPreferences prefs;
    private final Gson gson = new Gson();

    private final List<String> callList = new ArrayList<>();
    private final List<String> smsList = new ArrayList<>();
    private String priorityPhone = "";
    private boolean isPickingForCall = true;

    private ActivityResultLauncher<Intent> contactPickerLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        prefs = getSharedPreferences("SosNowPrefs", Context.MODE_PRIVATE);

        Toolbar toolbar = findViewById(R.id.toolbarSettings);
        setSupportActionBar(toolbar);
        if (toolbar != null) toolbar.setNavigationOnClickListener(v -> finish());

        etCallInput = findViewById(R.id.etCallInput);
        etSmsInput = findViewById(R.id.etSmsInput);
        containerSavedCalls = findViewById(R.id.containerSavedCalls);
        containerSavedSms = findViewById(R.id.containerSavedSms);
        containerHelplines = findViewById(R.id.containerHelplines);
        pickerTimerSeconds = findViewById(R.id.pickerTimerSeconds);
        tvTimerLabel = findViewById(R.id.tvTimerLabel);

        findViewById(R.id.btnOpenDashboard).setOnClickListener(v -> {
            startActivity(new Intent(this, DashboardActivity.class));
        });

        contactPickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                        extractPhone(result.getData().getData());
                    }
                }
        );

        setupTimerWheel();
        loadSavedData();
        loadHelplinesFromCloud();

        findViewById(R.id.btnAddCall).setOnClickListener(v -> {
            String num = sanitize10Digit(etCallInput.getText().toString());
            if (num != null) {
                if (!callList.contains(num)) {
                    callList.add(num);
                    if (priorityPhone.isEmpty()) priorityPhone = num;
                    saveCallData();
                    refreshCallRows();
                    etCallInput.setText("");
                    Toast.makeText(this, "Call contact add ho gaya!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Yeh number pehle se add hai", Toast.LENGTH_SHORT).show();
                }
            }
        });

        findViewById(R.id.btnAddSms).setOnClickListener(v -> {
            String num = sanitize10Digit(etSmsInput.getText().toString());
            if (num != null) {
                if (!smsList.contains(num)) {
                    smsList.add(num);
                    saveSmsData();
                    refreshSmsRows();
                    etSmsInput.setText("");
                    Toast.makeText(this, "SMS contact add ho gaya!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Yeh number pehle se add hai", Toast.LENGTH_SHORT).show();
                }
            }
        });

        findViewById(R.id.btnPickCallContact).setOnClickListener(v -> {
            isPickingForCall = true;
            openContacts();
        });

        findViewById(R.id.btnPickSmsContact).setOnClickListener(v -> {
            isPickingForCall = false;
            openContacts();
        });
    }

    private String sanitize10Digit(String raw) {
        if (raw == null) return null;
        String digits = raw.replaceAll("[^0-9]", "");
        if (digits.length() > 10) {
            digits = digits.substring(digits.length() - 10);
        }
        if (digits.matches("^[6-9]\\d{9}$")) {
            return digits;
        }
        Toast.makeText(this, "Kripya valid 10-digit mobile number daalein (e.g. 9876543210)", Toast.LENGTH_SHORT).show();
        return null;
    }

    private void openContacts() {
        Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
        contactPickerLauncher.launch(i);
    }

    private void extractPhone(Uri uri) {
        if (uri == null) return;
        try (Cursor c = getContentResolver().query(uri, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, null)) {
            if (c != null && c.moveToFirst()) {
                String num = sanitize10Digit(c.getString(0));
                if (num != null) {
                    if (isPickingForCall) {
                        etCallInput.setText(num);
                    } else {
                        etSmsInput.setText(num);
                    }
                }
            }
        } catch (Exception ignored) {}
    }

    private void setupTimerWheel() {
        pickerTimerSeconds.setMinValue(1);
        pickerTimerSeconds.setMaxValue(10);
        int current = prefs.getInt("TRIGGER_DELAY", 2);
        pickerTimerSeconds.setValue(current);
        tvTimerLabel.setText("Selected: " + current + " Seconds");

        pickerTimerSeconds.setOnValueChangedListener((p, o, n) -> {
            prefs.edit().putInt("TRIGGER_DELAY", n).apply();
            tvTimerLabel.setText("Selected: " + n + " Seconds");
            Toast.makeText(this, "Timer set to " + n + "s", Toast.LENGTH_SHORT).show();
        });
    }

    private void loadSavedData() {
        Type t = new TypeToken<ArrayList<String>>() {}.getType();
        String c = prefs.getString("CALL_CONTACTS", null);
        priorityPhone = prefs.getString("PRIORITY_CALL_PHONE", "");
        if (c != null) callList.addAll(gson.fromJson(c, t));

        String s = prefs.getString("SMS_CONTACTS", null);
        if (s != null) smsList.addAll(gson.fromJson(s, t));

        refreshCallRows();
        refreshSmsRows();
    }

    private void refreshCallRows() {
        containerSavedCalls.removeAllViews();
        for (String ph : callList) {
            View v = LayoutInflater.from(this).inflate(R.layout.item_saved_contact, containerSavedCalls, false);
            TextView tv = v.findViewById(R.id.tvSavedNumber);
            View badge = v.findViewById(R.id.tvPriorityBadge);
            MaterialButton btnPri = v.findViewById(R.id.btnMakePriority);
            ImageButton btnDel = v.findViewById(R.id.btnDeleteSaved);

            tv.setText(ph);
            if (ph.equals(priorityPhone)) {
                badge.setVisibility(View.VISIBLE);
                btnPri.setVisibility(View.GONE);
            } else {
                badge.setVisibility(View.GONE);
                btnPri.setVisibility(View.VISIBLE);
            }

            btnPri.setOnClickListener(x -> {
                priorityPhone = ph;
                saveCallData();
                refreshCallRows();
                Toast.makeText(this, "Priority set to " + ph, Toast.LENGTH_SHORT).show();
            });

            btnDel.setOnClickListener(x -> {
                callList.remove(ph);
                if (ph.equals(priorityPhone)) {
                    priorityPhone = callList.isEmpty() ? "" : callList.get(0);
                }
                saveCallData();
                refreshCallRows();
                Toast.makeText(this, "Contact hata diya gaya", Toast.LENGTH_SHORT).show();
            });
            containerSavedCalls.addView(v);
        }
    }

    private void refreshSmsRows() {
        containerSavedSms.removeAllViews();
        for (String ph : smsList) {
            View v = LayoutInflater.from(this).inflate(R.layout.item_saved_contact, containerSavedSms, false);
            TextView tv = v.findViewById(R.id.tvSavedNumber);
            ImageButton btnDel = v.findViewById(R.id.btnDeleteSaved);
            tv.setText(ph);

            btnDel.setOnClickListener(x -> {
                smsList.remove(ph);
                saveSmsData();
                refreshSmsRows();
                Toast.makeText(this, "Contact hata diya gaya", Toast.LENGTH_SHORT).show();
            });
            containerSavedSms.addView(v);
        }
    }

    private void loadHelplinesFromCloud() {
        new Thread(() -> {
            try {
                URL url = new URL(AppConfig.SERVER_BASE_URL + "?action=get_helplines");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) sb.append(line);
                r.close();

                JSONObject res = new JSONObject(sb.toString());
                JSONArray arr = res.getJSONArray("helplines");

                new Handler(Looper.getMainLooper()).post(() -> {
                    containerHelplines.removeAllViews();
                    for (int i = 0; i < arr.length(); i++) {
                        JSONObject h = arr.optJSONObject(i);
                        if (h == null) continue;
                        TextView tv = new TextView(this);
                        tv.setText("• " + h.optString("title") + ": " + h.optString("tollfree_number"));
                        tv.setTextSize(14);
                        tv.setTextColor(0xFF0284C7);
                        tv.setPadding(0, 6, 0, 6);
                        tv.setOnClickListener(click -> {
                            Intent dial = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + h.optString("tollfree_number")));
                            startActivity(dial);
                        });
                        containerHelplines.addView(tv);
                    }
                });
            } catch (Exception ignored) {}
        }).start();
    }

    private void saveCallData() {
        prefs.edit().putString("CALL_CONTACTS", gson.toJson(callList)).putString("PRIORITY_CALL_PHONE", priorityPhone).apply();
    }

    private void saveSmsData() {
        prefs.edit().putString("SMS_CONTACTS", gson.toJson(smsList)).apply();
    }
}