package com.mytatvarnsdk.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.RadioButton
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.CatalystInstance
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.mytatvarnsdk.CgmTrackyLibModule
import com.mytatvarnsdk.R
import com.mytatvarnsdk.databinding.ActivityHelpBinding
import org.json.JSONObject

class HelpActivity : AppCompatActivity() {
    private lateinit var binding: ActivityHelpBinding
    private val reactContext = CgmTrackyLibModule.mReactContext


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHelpBinding.inflate(layoutInflater)
        setContentView(binding.root)

        enableEdgeToEdge()

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        init()
    }

    private fun init() {
        val jsonObject = JSONObject()
        jsonObject.put("screen_name", intent.getStringExtra("ScreenName"))
        sendDataToRN(jsonObject.toString(), "cgm_WA_support_clicked")

        binding.btnProceed.setOnClickListener {
            val selectedRadioButtonId = binding.helpOptionsGroup.checkedRadioButtonId

            if (selectedRadioButtonId != -1) {
                val selectedRadioButton = findViewById<RadioButton>(selectedRadioButtonId)
                val selectedText = selectedRadioButton.text.toString()

                val jsonObject = JSONObject()
                jsonObject.put("help", selectedText)
                sendDataToRN(jsonObject.toString(), "cgm_WA_support_proceed_clicked")
            }

            openWhatsApp()
        }

        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.tvBack.setOnClickListener {
            finish()
        }

        enableDisableBtn(false)

        binding.helpOptionsGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.radio_purchase -> {
                    enableDisableBtn(true)
                }

                R.id.radio_connect -> {
                    enableDisableBtn(true)
                }

                R.id.radio_troubles -> {
                    enableDisableBtn(true)
                }

                else -> {
                    enableDisableBtn(false)
                }
            }
        }

        val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                finish()
            }
        }
        onBackPressedDispatcher.addCallback(this, callback)
    }

    fun enableDisableBtn(isEnable: Boolean) {
        binding.btnProceed.isEnabled = isEnable
        if (isEnable) {
            binding.btnProceed.alpha = 1f
        } else {
            binding.btnProceed.alpha = 0.5f
        }
    }

    private fun openWhatsApp() {
        val waBotUrl = "https://wa.aisensy.com/aaa1qv"
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(waBotUrl))
        try {
            // You don't need to set the package for browser-based WhatsApp bots
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "Error opening WhatsApp Bot", Toast.LENGTH_SHORT).show()
        }
    }

    private fun sendDataToRN(data: String, status: String) {
        if (reactContext != null) {
            try {
                val catalystInstance: CatalystInstance = reactContext.catalystInstance
                val module = catalystInstance.getNativeModule(CgmTrackyLibModule::class.java)

                if (module == null) {
                    sendDataToRNDirectly(data, status)
                    Log.d("sendDataToRN: ", "Module null")
                } else {
                    module.sendDataToReact(data, status, "cgmDeviceEvent")
                    Log.d("sendDataToRN: ", "Module is not null")
                }
            } catch (e: Exception) {
                Log.e("sendDataToRN: Error ", e.message.toString())
            }
        } else {
            Log.e("TrackyActivity", "ReactApplicationContext is null")
        }
    }

    private fun sendDataToRNDirectly(data: String, status: String) {
        try {
            val map: WritableMap = Arguments.createMap().apply {
                putString("data", data)
                putString("status", status)
            }

            reactContext?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                ?.emit("cgmDeviceEvent", map)
        } catch (e: Exception) {
            Log.e("sendDataToRNDirectly", "Error sending data to React", e)
        }
    }
}
