package com.mytatvarnsdk.activity

import android.app.Dialog
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toDrawable
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.CgmTrackyLibModule.Companion.mReactContext
import com.mytatvarnsdk.R
import com.mytatvarnsdk.databinding.ActivityStartCgmactivityBinding
import com.mytatvarnsdk.databinding.ExitDialogBottomsheetBinding


class StartCGMActivity : AppCompatActivity() {
    private lateinit var binding: ActivityStartCgmactivityBinding
    private var isForReconnect: Boolean = false
    private val reactContext = CgmTrackyLibModule.mReactContext
    private val bluetoothAdapter: BluetoothAdapter? by lazy {
        BluetoothAdapter.getDefaultAdapter()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityStartCgmactivityBinding.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() {
        isForReconnect = intent.getBooleanExtra("IsForReconnect", false)
        val envType = intent.getStringExtra("envType") ?: "prod"

        // Use envType as needed

        sendDataToRN("", "cgm_start_connection_landing")

        if (isForReconnect) {
            binding.commonButton.tvProceed.text = "Start Reconnection Journey"
        } else {
            binding.commonButton.tvProceed.text = "Start Connection Journey"
        }

        binding.commonButton.btnProceed.setOnClickListener {
            sendDataToRN("", "cgm_start_connection_journey_clicked")

            if (isForReconnect) {
                val intent = if (areAllPermissionsGranted() && bluetoothAdapter!!.isEnabled) {
                    Intent(this, SearchTransmitterActivity::class.java).putExtra(
                        "IsForReconnect",
                        true
                    )
                } else {
                    Intent(this, PermissionActivity::class.java).putExtra(
                        "IsForReconnect",
                        true
                    )
                }
                startActivity(intent)
            } else {
                startActivity(Intent(this@StartCGMActivity, PermissionActivity::class.java))
            }
            finish()
        }

        binding.toolbar.btnClose.setOnClickListener {
            openExitDialog()
        }

        binding.toolbar.btnWhatsapp.setOnClickListener {
            startActivity(
                Intent(this, HelpActivity::class.java)
                    .putExtra("ScreenName", "connection journey page")
            )
        }

        binding.toolbar.btnWatchDemo.setOnClickListener {
            sendDataToRN("", "cgm_watch_demo_clicked")
            startActivity(
                Intent(this, VideoActivity::class.java).putExtra(
                    "VideoId",
                    if (isForReconnect) "n_pUrFoZ1wQ" else "r5Zemc4R044"
                )
            )
        }

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

    private fun areAllPermissionsGranted(): Boolean {
        val requiredPermissions = mutableListOf<String>()

        // Add Bluetooth permissions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requiredPermissions.addAll(PermissionUtils.BLUETOOTH_S)
        }

        // Add location permissions
        requiredPermissions.addAll(PermissionUtils.LOCAL_PERMISSION)

        return requiredPermissions.all {
            ContextCompat.checkSelfPermission(
                mReactContext!!,
                it
            ) == PackageManager.PERMISSION_GRANTED
        }
    }


    private fun openExitDialog() {
        val binding = ExitDialogBottomsheetBinding.inflate(layoutInflater)

        val dialog = Dialog(this)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(binding.root)

        val window = dialog.window
        window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        window?.setGravity(Gravity.BOTTOM)
        window?.setBackgroundDrawable(Color.TRANSPARENT.toDrawable())

        binding.btnExit.tvProceed.text = "Exit"

        binding.btnExit.root.setOnClickListener(View.OnClickListener { v: View? ->
            dialog.dismiss()
            finish()
        })

        binding.btnCancel.root.setOnClickListener(View.OnClickListener { v: View? ->
            dialog.dismiss()
        })

        binding.closeButton.setOnClickListener(View.OnClickListener { v: View? ->
            dialog.dismiss()
        })

        dialog.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)
        }
    }

}
