package com.mytatvarnsdk.activity

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
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.graphics.drawable.toDrawable
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import cgmblelib.utils.SharedPreferencesLibraryUtil
import com.bumptech.glide.Glide
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.ActivitySensorConnectSuccessBinding
import com.mytatvarnsdk.databinding.ExitDialogBottomsheetBinding
import com.mytatvarnsdk.myView.progress.ProgressManagement
import com.mytatvarnsdk.myView.progress.ProgressType
import com.mytatvarnsdk.network.AuthenticateSDKService
import com.mytatvarnsdk.network.AuthenticateSDKService.LoaderListener
import com.mytatvarnsdk.utils.DeviceStatus
import com.mytatvarnsdk.utils.TATVA_ENVIRONMENT
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


class SensorConnectSuccessActivity : AppCompatActivity() {
    private lateinit var binding: ActivitySensorConnectSuccessBinding
    lateinit var authenticateSDKService: AuthenticateSDKService
    private val job = Job()
    private val scope = CoroutineScope(Dispatchers.IO + job)
    private var isForReconnect: Boolean = false
    private val reactContext = CgmTrackyLibModule.mReactContext

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySensorConnectSuccessBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)
        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)

        sendDataToRN("", "cgm_sensor_connection_successful")

        val formatter = SimpleDateFormat("hh:mm a", Locale.getDefault())
        binding.tvDateTime.text = "Connected on ${formatter.format(Date()).uppercase()}"

        Glide.with(this)
            .asGif()
            .load(R.drawable.success_anim)
            .into(binding.ivSuccess)

        authenticateSDKService = AuthenticateSDKService(scope = scope)

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

        binding.toolbar.btnWatchDemo.setOnClickListener {
            sendDataToRN("", "cgm_watch_demo_clicked")

            startActivity(
                Intent(this, VideoActivity::class.java).putExtra(
                    "VideoId",
                    if (isForReconnect) "n_pUrFoZ1wQ" else "r5Zemc4R044"
                )
            )
        }

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

            if (isForReconnect) {
                startActivity(Intent(this, PlaceTransmitterActivity::class.java))
            } else {
                startActivity(Intent(this, PlaceSensorActivity::class.java))
            }
            finish()
        }

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

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

        postEventDataToAPI()
    }

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

    private fun postEventDataToAPI() {
        val sharedPreferencesLibraryUtil = SharedPreferencesLibraryUtil(this)
        val information = sharedPreferencesLibraryUtil.qrInformation

        val rawData = JSONObject()
        rawData.put("transmitterName", information.transmitterName)
        rawData.put("SensorId", information.sensor)
        rawData.put("R", information.r)
        rawData.put("K", information.k)
        rawData.put("Sensor", information.sensor)
        rawData.put("timeInMillis", information.timeInMillis)

        val obj = JSONObject()
        obj.put("sensorId", information.sensor)
        obj.put("status", DeviceStatus.CONNECTED.id)
        obj.put("rawData", rawData)

        authenticateSDKService.postDeviceData(
            environment = if (CgmTrackyLibModule.env.lowercase() == "uat") TATVA_ENVIRONMENT.STAGE else TATVA_ENVIRONMENT.PROD,
            data = obj.toString(),
            token = CgmTrackyLibModule.userToken,
            loaderListener = object : LoaderListener {
                override fun onShowLoader() {
                    ProgressManagement.getInstance()
                        .showWait(
                            this@SensorConnectSuccessActivity,
                            ProgressType.PROGRESSDIALOG_CONNECT,
                            null
                        )
                }

                override fun onHideLoader() {
                    ProgressManagement.getInstance().dismissWait(this@SensorConnectSuccessActivity)
                }
            }
        )
    }

    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? ->
            finish()
            dialog.dismiss()
        })

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

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

        dialog.show()
    }

}
