package cpm.com.gskmtorange.dailyentry

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.lifecycle.lifecycleScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.sj.camera_lib_android.Database.ReactPendingData
import com.sj.camera_lib_android.Database.ReactSingleImage
import com.sj.camera_lib_android.models.ImageUploadModel
import com.sj.camera_lib_android.utils.CameraSDK
import cpm.com.gskmtorange.Database.GSKOrangeDB
import cpm.com.gskmtorange.GetterSetter.CategoryPictureGetterSetter
import cpm.com.gskmtorange.R
import cpm.com.gskmtorange.adapter.SubCatPdAdapter
import cpm.com.gskmtorange.adapter.data.ImageUri
import cpm.com.gskmtorange.constant.CommonFunctions
import cpm.com.gskmtorange.constant.CommonFunctions.savefile
import cpm.com.gskmtorange.constant.CommonString
import cpm.com.gskmtorange.constant.CommonUtils
import cpm.com.gskmtorange.databinding.ActivityPdimageBinding
import cpm.com.gskmtorange.xmlGetterSetter.Master_Storelist_PDA_GetterSetter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.File

class PDimageActivity : AppCompatActivity() {
    private var context: Context? = null
    var categoryName: String? = null
    var categoryId: String? = null
    var store_id: String? = null;
    var date: String? = null;
    var lang: String? = null;
    var userId: String? = null
    var store_type_id: String? = null
    var class_id: String? = null
    var key_account_id: String? = null
    var country_id: String? = null
    var store_flag_str: String? = null
    private var preferences: SharedPreferences? = null
    var db: GSKOrangeDB? = null
    var listdat: ArrayList<CategoryPictureGetterSetter>? = ArrayList()
    var masterStoreListPd: ArrayList<Master_Storelist_PDA_GetterSetter>? = ArrayList()
    var username: String? = ""
    var toggle: String? =  "1"
    private var kpi_name: String? = ""
    private lateinit var binding: ActivityPdimageBinding
    private var adapter: SubCatPdAdapter? = null
    val PERMISSION_ALL: Int = 99
    private var _pos = -1;
    var devicename : String? = ""
    var store_name : String? = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPdimageBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)
        context = this
        db = GSKOrangeDB(context)
        preferences = PreferenceManager.getDefaultSharedPreferences(context)
        db?.open()
        preferences?.let {
            lang = it.getString(CommonString.KEY_LANGUAGE, "")
            store_id = it.getString(CommonString.KEY_STORE_ID, "")
            store_name = it.getString(CommonString.KEY_STORE_NAME, "")
            username = it.getString(CommonString.KEY_USERNAME, "")
            store_type_id = it.getString(CommonString.KEY_STORETYPE_ID, "")
            class_id = it.getString(CommonString.KEY_CLASS_ID, "")
            key_account_id = it.getString(CommonString.KEY_KEYACCOUNT_ID, "")
            country_id = it.getString(CommonString.KEY_COUNTRY_ID, "")
            store_flag_str = it.getString(CommonString.KEY_STORE_FLAG, "")
            date = it.getString(CommonString.KEY_DATE, "")
        }
        devicename = android.os.Build.MANUFACTURER
       // Log.d("device_name",devicename.toString())

        CommonFunctions.updateLangResources(
            context, preferences?.getString(CommonString.KEY_LANGUAGE, "")
        )
        intent?.let {
            categoryName = it.getStringExtra("categoryName")
            categoryId = it.getStringExtra("categoryId")
            kpi_name = it.getStringExtra("kpi_name")
        }
        supportActionBar?.apply {
            setHomeButtonEnabled(true)
            setDisplayHomeAsUpEnabled(true)
            title = kpi_name
        }
        masterStoreListPd = db?.getMasterStoreListPd(store_id,CommonString.TABLE_MASTER_STORELIST_PD)
       // Log.d("master_store_list_size",masterStoreListPd.toString())


        binding.rlContent.btntoggle.setOnClickListener {
                if(toggle =="1"){
                    toggle = "0"
                    binding.rlContent.recyclerViewSubCat.visibility = View.GONE
                    binding.rlContent.btntoggle.isChecked = false
                }
                else{
                    toggle = "1"
                    binding.rlContent.recyclerViewSubCat.visibility = View.VISIBLE
                    binding.rlContent.btntoggle.isChecked = true
                    Log.d("toggle_value_new",toggle.toString())
                }
            }
        preferences?.getString(CommonString.KEY_PD_PROJECT_Id, "")?.let { projectId ->
             userId = preferences?.getString(CommonString.KEY_PD_USER_Id, "")
                .takeIf { !it.isNullOrBlank() } ?: username
          //  Log.d("pd_user_id",userId.toString());

            CommonUtils.initializePDSDK(
                this@PDimageActivity,
                projectId = projectId,
                _userId = userId
            )
        }
        registerIntentFilter(
            listOf(
                "DataSaved", "did-receive-queue-data", "did-receive-image-upload-status"
            )
        )

        binding.apply {
            fab.setOnClickListener {
                if (validate()) {
                    val builder = AlertDialog.Builder(this@PDimageActivity)
                    builder.setMessage(getString(R.string.check_save_message)).setCancelable(false)
                        .setPositiveButton(getString(R.string.yes)) { dialog, _ ->
                            // Handle Yes button click
                            db?.open()
                            db?.InsertPdImageData(
                                date,
                                store_id,
                                categoryId,
                                listdat,
                                toggle,
                                CommonString.KEY_COMPELETE
                            )?.let {
                                if (it > 0) {
                                    Snackbar.make(
                                        binding.fab,
                                        resources.getString(R.string.save_message),
                                        Snackbar.LENGTH_LONG
                                    ).setAction("Action", null).show()
                                    lifecycleScope.launch {
                                        delay(3000) // 3 seconds delay
                                        val intent = Intent(this@PDimageActivity, PD_Realtime_Report::class.java)
                                        intent.putExtra("categoryName", categoryName)
                                        intent.putExtra("categoryId", categoryId)
                                        intent.putExtra("kpi_name", "IR Realtime Analytics")
                                        startActivity(intent)
                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out)
                                        finish()
                                    }
                                } else {
                                    Snackbar.make(
                                        binding.fab,
                                        resources.getString(R.string.save_message),
                                        Snackbar.LENGTH_LONG
                                    ).setAction("Action", null).show()
                                }
                            }
                            dialog.dismiss()
                        }.setNegativeButton(getString(R.string.no)) { dialog, _ ->
                            dialog.cancel()
                        }
                    val alert = builder.create()
                    alert.show()
                }
            }
        }
        callAdapter()
        //  checkAndRequestPermissions()
    }

    override fun onResume() {
        super.onResume()
        CommonFunctions.updateLangResources(
            context,
            preferences!!.getString(CommonString.KEY_LANGUAGE, "")
        )

        db?.open()
    }

    private fun validate(): Boolean {
        var checkFlag = true // Use local variable to avoid issues
        if (!listdat.isNullOrEmpty() && toggle=="1") {
            for (data in listdat!!) {  // Use standard loop for better control
                if (data.imageUris.isNullOrEmpty()) {
                    checkFlag = false // Set false if validation fails
                    Snackbar.make(
                        binding.fab,
                        "Please capture IR images of ${data.suB_CATEGORY}",
                        Snackbar.LENGTH_SHORT
                    ).show()
                    break // Stop further checks once an issue is found
                }
            }
        }
        return checkFlag // Correctly return validation result
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item.itemId
        if (id == android.R.id.home) {
            //showDataLossAlert();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out)
            finish()
        }
        if (id == R.id.action_settings) {
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        LocalBroadcastManager.getInstance(this@PDimageActivity)
            .unregisterReceiver(myBroadcastReceiver) // onDestroy
    }

    private fun registerIntentFilter(filters: List<String> = listOf()) {
        filters.forEach { filter ->
            LocalBroadcastManager.getInstance(this@PDimageActivity)
                .registerReceiver(myBroadcastReceiver, IntentFilter(filter))
        }
    }

    private val savedImages = mutableListOf<ImageUri>()
    private var myBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                "did-receive-queue-data" -> {
                    val receivedList =
                        intent.getParcelableArrayListExtra<ReactPendingData>("imageList")
                    Log.d("DEBUG-LOG did-receive-queue-data", "$receivedList")
                    if (receivedList.isNullOrEmpty()) {
                        CameraSDK.uploadFailedImage(this@PDimageActivity)
                    }
                }

                "did-receive-image-upload-status" -> {
                    val receivedImage = intent.getParcelableExtra<ReactSingleImage>("image")
                    Log.d("DEBUG-LOG did-receive-image-upload-status", "$receivedImage")
                }

                "DataSaved" -> {
                    val receivedList =
                        intent.getParcelableArrayListExtra<ImageUploadModel>("imageListSaved")
                    Log.d("DEBUG-LOG DataSaved", "$receivedList")
                    receivedList?.let {
                        savedImages.clear()
                        it.forEach { item ->
                            val dir = CommonString.getImagesFolder(context)
                            val setName =
                                store_id + "_" + username?.replace(".", "") + "_IRPDIMG-" + File(
                                    item.uri
                                ).getName()
                            savedImages.add(ImageUri(uri = item.uri, modify_uri = setName))
                            savefile(item.uri.toUri(), "$dir $setName")
                        }
                        adapter?.updateItem(position = _pos, savedImages)
                        Log.e("savedImages", savedImages.toString())
                        _pos = -1
                    }
                }
            }
        }
    }

    private fun launchCamera(subCat_code: String) {
        val uploadFrom = "TestApp"
        val masterstorelistpddata = masterStoreListPd?.getOrNull(0)
        val metadata = JSONObject().apply {
            put("Device_Name", devicename ?: "NA")
            put("username", username ?: "NA")
            put("shop_name", store_name ?: "NA")
            put("parinaam_id", masterstorelistpddata?.storeId?.getOrNull(0) ?: "NA") //storeid
            put("channel", masterstorelistpddata?.channel?.getOrNull(0) ?: "NA")
            put("format", masterstorelistpddata?.format?.getOrNull(0) ?: "NA")
            put("region", masterstorelistpddata?.region?.getOrNull(0) ?: "NA")
            put("bay_type", masterstorelistpddata?.bay_type?.getOrNull(0) ?: "NA")
            put("no_of_bays", masterstorelistpddata?.no_of_bays?.getOrNull(0) ?: "NA")
            put("category", categoryName?: "NA")
            put("user_id", masterstorelistpddata?.user_id?.getOrNull(0) ?: "NA")
            put("Active", masterstorelistpddata?.active?.getOrNull(0) ?: "NA")
            put("ASMArea", masterstorelistpddata?.asmArea?.getOrNull(0) ?: "NA")
            put("EmployeeName", masterstorelistpddata?.employeeName?.getOrNull(0) ?: "NA")
            put("DesignationName", masterstorelistpddata?.designationName?.getOrNull(0) ?: "NA")
            put("SupervisorId", masterstorelistpddata?.supervisorId?.getOrNull(0) ?: "NA")
            put("Supervisor", masterstorelistpddata?.supervisor?.getOrNull(0) ?: "NA")
            put("StoreCode", masterstorelistpddata?.storeCode?.getOrNull(0) ?: "NA")
            put("ChainId", masterstorelistpddata?.chainId?.getOrNull(0) ?: "NA")
            put("StoreTypeId", masterstorelistpddata?.storeTypeId?.getOrNull(0) ?: "NA")
            put("SOName", masterstorelistpddata?.soName?.getOrNull(0) ?: "NA")
        }
        val uploadParams = JSONObject().apply {
            put("shop_id", store_id)
            put("project_id", preferences?.getString(CommonString.KEY_PD_PROJECT_Id, ""))
            put("shelf_type", "Primary Shelf")
            put("category_id", subCat_code)
            put("user_id", userId)
         //   put("user_id", userId)
            put("metadata", metadata)
        }

        //   "metadata": { "Device_Name": $devicename,"Username": $username }
       /* uploadParams.put("shop_id", store_id)
        uploadParams.put("user_id", username)
        uploadParams.put("category_id", subCat_code)
        uploadParams.put("project_id", preferences?.getString(CommonString.KEY_PD_PROJECT_Id, ""))*/

        Log.d("uploadParams", uploadParams.toString())
        if(!lang.equals("ENGLISH",ignoreCase = true)){
            CameraSDK.startCamera(
                context = this,
                orientation = "",
                widthPercentage = 20,
                uploadParams = uploadParams,
                resolution = 3000,
                referenceUrl = "",
                allowBlurCheck = true,
                allowCrop = true,
                uploadFrom = uploadFrom,
                isRetake = false,
                showOverlapToggleButton = false,
                showGridLines = true,
                zoomLevel = 1.0,
                language_code = "ar",
                isLambda = false
            )
        }
        else{
            CameraSDK.startCamera(
                context = this,
                orientation = "",
                widthPercentage = 20,
                uploadParams = uploadParams,
                resolution = 3000,
                referenceUrl = "",
                allowBlurCheck = true,
                allowCrop = true,
                uploadFrom = uploadFrom,
                isRetake = false,
                showOverlapToggleButton = false,
                showGridLines = true,
                zoomLevel = 1.0,
                language_code = "en",
                isLambda = false
            )
        }
    }

    private fun callAdapter() {
        if (country_id == "8") {
            db?.open()
            listdat = db?.getCategoryPicturedata(
                date,
                categoryId,
                null,
                null,
                null,
                store_id,
                CommonString.TABLE_MAPPING_STOCK_STOREWISE
            )
        } else if (store_flag_str.equals(CommonString.FROM_DEVIATION, ignoreCase = true)) {
            db?.open()
            listdat = db?.getCategoryPicturedata(
                date,
                categoryId,
                key_account_id,
                store_type_id,
                class_id,
                store_id,
                CommonString.TABLE_MAPPING_STOCK_ADHOC
            )
        } else {
            db?.open()
            listdat = db?.getCategoryPicturedata(
                date,
                categoryId,
                key_account_id,
                store_type_id,
                class_id,
                store_id,
                CommonString.TABLE_MAPPING_STOCK
            )
        }
        adapter = SubCatPdAdapter(
            category = categoryName,
            context = this,
            subcates = ArrayList(),
            btnlistener = object : SubCatPdAdapter.BtnClickListener {
                override fun onStartSessionClick(_pos: Int, data: CategoryPictureGetterSetter) {
                    this@PDimageActivity._pos = _pos
                    launchCamera(data.subCatCode)
                }
            })
        binding.rlContent.apply {
                recyclerViewSubCat.adapter = adapter
                recyclerViewSubCat.layoutManager = LinearLayoutManager(this@PDimageActivity)
                adapter?.addsubCatItems(listdat)
            }
        // Now only handle toggle visibility
        toggle = listdat?.get(0)?.toggle_value ?: "1"

        if(toggle == "1"){
            binding.rlContent.recyclerViewSubCat.visibility = View.VISIBLE
            binding.rlContent.btntoggle.isChecked = true
        } else {
            binding.rlContent.recyclerViewSubCat.visibility = View.GONE
            binding.rlContent.btntoggle.isChecked = false
        }
        }

    override fun onPause() {
        super.onPause()
        db?.open()
        if (!db!!.isSOSCategory(store_id, date, CommonString.KEY_COMPELETE, categoryId)) {
            db?.InsertPdImageData(date, store_id, categoryId, listdat,toggle, CommonString.KEY_DRAFT)
        }
    }
}