package es.verdnatura.presentation.view.feature.packaging.fragment

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPackagingBinding
import es.verdnatura.domain.ConstAndValues.ENTRYID
import es.verdnatura.domain.ConstAndValues.ENTRYOBSERVATIONORIGINAL
import es.verdnatura.domain.ConstAndValues.SUPPLIERID
import es.verdnatura.domain.ConstAndValues.SUPPLIERNAME
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.inventario.fragment.SearchSupplierModel
import es.verdnatura.presentation.view.feature.packaging.model.EntrySalix
import es.verdnatura.presentation.view.feature.packaging.model.Supplier
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import ir.mirrajabi.searchdialog.SimpleSearchDialogCompat
import kotlinx.coroutines.runBlocking

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class SupplierFragment(
    var entryPoint: String = ""

) : BaseFragment<FragmentPackagingBinding, SupplierViewModel>(
    SupplierViewModel::class
) {

    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var layoutManager: LinearLayoutManager? = null
    private var onBack = false
    private val suppliers = ArrayList<SearchSupplierModel>()
    private val entries = ArrayList<SearchSupplierModel>()
    private lateinit var customDialog: CustomDialog

    companion object {
        fun newInstance(entryPoint: String) = SupplierFragment(entryPoint)
    }

    override fun getLayoutId(): Int = R.layout.fragment_packaging

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        viewModel.getSuppliers()
        super.onCreate(savedInstanceState)
    }

    override fun onPause() {
        onBack = true
        super.onPause()

    }

    override fun init() {
        binding.filterSupplier.setOnClickListener {
            SimpleSearchDialogCompat(
                context,
                getString(R.string.suppliers),
                getString(R.string.escribirparteNombre),
                null,
                suppliers
            ) { baseSearchDialogCompat, nombre, position ->
                binding.filterSupplier.text = (nombre.getName())
                runBlocking {
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        SUPPLIERNAME,
                        nombre.getName()
                    )
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        SUPPLIERID,
                        nombre.getId().toInt()
                    )
                }
                viewModel.getEntriesFromSupplier(nombre.getId().toInt())
                baseSearchDialogCompat.dismiss()
            }.show()
        }
        customDialog = CustomDialog(requireContext())
        ma.hideBottomNavigation(View.GONE)
        setToolBar()
        setEvents()

        super.init()
    }

    private fun setToolBar() {
        binding.mainToolbar.toolbarTitle.text = entryPoint
    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

    }

    private fun setEntryDialog() {
        binding.filterEntry.visibility = View.VISIBLE
        binding.filterEntry.setOnClickListener {
            SimpleSearchDialogCompat(
                context,
                getString(R.string.entry),
                getString(R.string.escribirparteNombre),
                null,
                entries
            ) { baseSearchDialogCompat, nombre, position ->
                binding.filterEntry.text = nombre.getName()
                runBlocking {
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        ENTRYID,
                        nombre.getId().toInt()
                    )
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        ENTRYOBSERVATIONORIGINAL,
                        nombre.getObservation()
                    )
                    mobileApplication.dataStoreApp.deleteImages()
                }
                ma.onPasillerosItemClickListener(
                    PasillerosItemVO(title = R.string.titlePackagingCount),
                    getString(R.string.titlePackagingCount)
                )
                // }
                baseSearchDialogCompat.dismiss()
            }.show()
        }

    }

    override fun observeViewModel() {
        with(viewModel) {
            supplierList.observe(viewLifecycleOwner) {
                createSupplierList(it.list)
            }
            entryList.observe(viewLifecycleOwner) {
                createEntryList(it.list)
            }


            entry.observe(viewLifecycleOwner) {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, isError = true, isPlayed = false)

                } else {
                    runBlocking {
                        mobileApplication.dataStoreApp.editDataStoreKey("ENTRYID", it.id!!.toInt())
                    }

                    ma.onPasillerosItemClickListener(
                        PasillerosItemVO(title = R.string.titlePackagingCount),
                        getString(R.string.titlePackagingCount)
                    )
                }
            }
        }
    }

    private fun createSupplierList(list: List<Supplier>) {
        suppliers.clear()
        if (list.isNotEmpty())

            list.forEach { supplier ->

                try {
                    suppliers.add(
                        SearchSupplierModel(
                            supplier.name,
                            supplier.id.toString(),
                            observation = ""
                        )
                    )
                } catch (ex: Exception) {
                    ma.messageWithSound(
                        message = ex.message.toString(),
                        isError = true,
                        isPlayed = true
                    )
                }

            }
    }

    private fun createEntryList(list: List<EntrySalix>) {
        list.sortedBy { it.travel?.landed }
        entries.clear()
        list.forEach { entry ->
            if (!entry.isError) {

                try {
                    entries.add(
                        SearchSupplierModel(
                            entry.id.toString() + "->" + (entry.travel?.landed),
                            id = entry.id.toString(),
                            observation = entry.observation
                        )
                    )

                } catch (ex: Exception) {
                    ma.messageWithSound(
                        message = ex.message.toString(),
                        isError = true,
                        isPlayed = true
                    )
                }
            }
        }

        setEntryDialog()
    }

}

