package cpm.com.gskmtorange.dailyentry

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.DialogInterface
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.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.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 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 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: ActivityPdimageBinding
    private var adapter: SubCatPdAdapter? = null
    val PERMISSION_ALL: Int = 99
    private var _pos = -1;

    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 {
            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

            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,
                                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
                                        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()
        db?.open()
    }

    private fun validate(): Boolean {
        var checkFlag = true // Use local variable to avoid issues
        if (!listdat.isNullOrEmpty()) {
            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 uploadParams = JSONObject(
            """
                           {
                            "shop_id": 62475,
                            "project_id": "4f57635b-6b07-45bf-bfba-c61c2826b6db",
                            "td_version_id": 178,
                            "shelf_image_id": null,
                            "asset_image_id": null,
                            "shelf_type": "Primary Shelf",
                            "category_id": 123,
                            "user_id": 133,
                            "isConnected": true,
                            "sn_image_type": "skus",
                            "image_type": "multiple",
                            "seq_no": 1,
                            "level": 1,
                            "uploadOnlyOnWifi": 0,
                            "app_session_id": "8e2faa6b-d6fe-413a-a693-76a0cbe0ce71",
                            "metadata": { "Device_Name": "Samsung" }
                        }
                      """
        )
        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, ""))

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

        Log.d("listdatsize", listdat?.size.toString())
        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)
                    Log.d("subCatCode", data.subCatCode)
                }
            })
        binding.rlContent.apply {
            recyclerViewSubCat.adapter = adapter
            recyclerViewSubCat.layoutManager = LinearLayoutManager(this@PDimageActivity)
            adapter?.addsubCatItems(listdat)
        }
    }

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

    private fun checkAndRequestPermissions() {
        var read_phone_state = 0
        var write_storage = 0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            write_storage =
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            read_phone_state =
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
            write_storage =
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        val listPermissionsNeeded: MutableList<String> = java.util.ArrayList()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (write_storage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_MEDIA_IMAGES)
            }
        } else {
            if (write_storage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
        }

        if (listPermissionsNeeded.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                listPermissionsNeeded.toTypedArray<String>(),
                PERMISSION_ALL
            )
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSION_ALL) {
            val perms: MutableMap<String, Int> = HashMap()
            // Initialize the map with both permissions
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                perms[Manifest.permission.READ_MEDIA_IMAGES] = PackageManager.PERMISSION_GRANTED
            } else {
                perms[Manifest.permission.WRITE_EXTERNAL_STORAGE] =
                    PackageManager.PERMISSION_GRANTED
            }
            // Fill with actual results from user
            if (grantResults.isNotEmpty()) {
                for (i in permissions.indices) perms[permissions[i]] = grantResults[i]
                // Check for both permissions//
                if (perms[Manifest.permission.READ_MEDIA_IMAGES] == PackageManager.PERMISSION_GRANTED &&
                    perms[Manifest.permission.WRITE_EXTERNAL_STORAGE] == PackageManager.PERMISSION_GRANTED
                ) {
                    Log.d("", "sms & location services permission granted")
                } else {
                    Log.d("", "Some permissions are not granted ask again ")
                    if (ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.READ_MEDIA_IMAGES
                        ) ||
                        ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                        )
                    ) {
                        showDialogOK(
                            "Photos or media Service Permission required for this app"
                        ) { _: DialogInterface?, which: Int ->
                            when (which) {
                                DialogInterface.BUTTON_POSITIVE -> checkAndRequestPermissions()
                                DialogInterface.BUTTON_NEGATIVE -> {
                                    // proceed with logic by disabling the related features or quit the app.
                                    val startMain =
                                        Intent(Intent.ACTION_MAIN)
                                    startMain.addCategory(Intent.CATEGORY_HOME)
                                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                    startActivity(startMain)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun showDialogOK(message: String, okListener: DialogInterface.OnClickListener) {
        AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", okListener).create().show()
    }
}