package cpm.com.gskmtorange.dailyentry

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.view.MenuItem
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
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.RealtimeAdapter
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.ActivityPdRealtimeReportBinding
import cpm.com.gskmtorange.databinding.ActivityPdimageBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.io.File

class PD_Realtime_Report : 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 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 username: String? = ""
    private var kpi_name: String? = ""
    private lateinit var binding: ActivityPdRealtimeReportBinding
    private var adapter: RealtimeAdapter? = null
    val PERMISSION_ALL: Int = 99
    private var _pos = -1;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPdRealtimeReportBinding.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, "")
            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, "")
        }

        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
        }
        preferences?.getString(CommonString.KEY_PD_PROJECT_Id, "")?.let { projectId ->
            val userId = preferences?.getString(CommonString.KEY_PD_USER_Id, "")
                .takeIf { !it.isNullOrBlank() } ?: username
            Log.d("pd_user_id",userId.toString());

            CommonUtils.initializePDSDK(
                this@PD_Realtime_Report,
                projectId = projectId,
                _userId = userId
            )
        }

        registerIntentFilter(
            listOf(
                "DataSaved", "did-receive-queue-data", "did-receive-image-upload-status"
            )
        )
        callAdapter()
    }

    override fun onResume() {
        super.onResume()
        db?.open()
    }


    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@PD_Realtime_Report)
            .unregisterReceiver(myBroadcastReceiver) // onDestroy
    }

    private fun registerIntentFilter(filters: List<String> = listOf()) {
        filters.forEach { filter ->
            LocalBroadcastManager.getInstance(this@PD_Realtime_Report)
                .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@PD_Realtime_Report)
                    }
                }

                "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 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 = RealtimeAdapter(
            category = categoryName,
            context = this,
            subcates = ArrayList(),
            btnlistener = object : RealtimeAdapter.BtnClickListener {
                override fun onStartSessionClick(_pos: Int, data: CategoryPictureGetterSetter) {
                    this@PD_Realtime_Report._pos = _pos
                    val intent = Intent(this@PD_Realtime_Report, PD_Realtime_Report_Detail::class.java)
                    intent.putExtra("categoryName", categoryName)
                    intent.putExtra("categoryId", categoryId)
                    intent.putExtra("pd_subcat_code", data.subCatCode)
                    intent.putExtra("subcat_name", data.suB_CATEGORY)
                    intent.putExtra("kpi_name", "IR Realtime Report")
                    startActivity(intent)
                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out)
                   // launchCamera(data.subCatCode)
                   // Log.d("subCatCode", data.subCatCode)
                }
            })
        binding.rlContent.apply {
            recyclerViewSubCat.adapter = adapter
            recyclerViewSubCat.layoutManager = LinearLayoutManager(this@PD_Realtime_Report)
            adapter?.addsubCatItems(listdat)
        }
    }
}