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

import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPackagingSummaryBinding
import es.verdnatura.domain.ConstAndValues.ENTRYID
import es.verdnatura.domain.ConstAndValues.ENTRYNUMBERIMAGES
import es.verdnatura.domain.ConstAndValues.ENTRYOBSERVATIONS
import es.verdnatura.domain.ConstAndValues.SUPPLIERID
import es.verdnatura.domain.ConstAndValues.SUPPLIERNAME
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.TAG
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.addFragment
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.packaging.adapter.ItemSupplierAdapter
import es.verdnatura.presentation.view.feature.pasillero.fragment.PasilleroFragment
import kotlinx.coroutines.runBlocking

class PackagingSummaryFragment(
    var entryPoint: String = ""

) : BaseFragment<FragmentPackagingSummaryBinding, SupplierViewModel>(
    SupplierViewModel::class
) {
    private var adapteritemsupplier: ItemSupplierAdapter? = null
    private lateinit var customDialog: CustomDialog
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var layoutManager: LinearLayoutManager? = null

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

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

    override fun init() {
        customDialog = CustomDialog(requireContext())
        binding.totalImages.text =
            mobileApplication.dataStoreApp.readDataStoreKey<Int>(ENTRYNUMBERIMAGES).toString()
        binding.observations.text =
            mobileApplication.dataStoreApp.readDataStoreKey<String>(ENTRYOBSERVATIONS)


        viewModel.getItemsPackaging(
            mobileApplication.dataStoreApp.readDataStoreKey(SUPPLIERID),
            mobileApplication.dataStoreApp.readDataStoreKey(ENTRYID)
        )

        ma.hideBottomNavigation(View.GONE)

        setToolBar()
        setEvents()
        super.init()
    }

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text =
            mobileApplication.dataStoreApp.readDataStoreKey<String>(SUPPLIERNAME)

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconConfirm = ImageView(context)
        iconConfirm.setImageResource(R.drawable.check)
        iconConfirm.tooltipText = getString(R.string.confirmEntry)

        listIcons.add(iconConfirm)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    when (item) {
                        iconConfirm.drawable -> {
                            showWarning()
                        }
                    }
                }

            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)

    }

    private fun setEvents() {

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

    }

    override fun observeViewModel() {
        with(viewModel) {

            itemSupplierList.observe(viewLifecycleOwner) {

                val mySummaryList = it.list.filter { it.printedStickers > 0 }
                adapteritemsupplier =
                    ItemSupplierAdapter(mySummaryList, null, null, null, showItems = false)
                binding.itemsupplierRecyclerview.adapter = adapteritemsupplier
                layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
                binding.itemsupplierRecyclerview.layoutManager = layoutManager
            }
            responseNotification.observe(viewLifecycleOwner) {
                if (it == true) {
                    deleteDataEntry()
                } else {
                    ma.messageWithSound(
                        getString(R.string.errorEntriesNotification),
                        isError = true,
                        isPlayed = true
                    )
                }
            }
        }
    }

    private fun deleteDataEntry() {
        runBlocking {
            mobileApplication.dataStoreApp.deleteEntryPackaging()
            mobileApplication.dataStoreApp.deleteImages()
        }

        ma.addFragment(
            PasilleroFragment.newInstance(getString(R.string.main), true),
            R.id.main_frame_layout,
            PasilleroFragment.TAG,
            false
        )

    }

    private fun showWarning() {

        customDialog.setTitle(getString(R.string.sendEntry))
        customDialog.setTitle(getString(R.string.warningEntry))
            .setOkButton(
                getString(
                    R.string.accept
                )
            ) {
                viewModel.notificationQueues(
                    "modified-entry",
                    mobileApplication.userId!!,
                    """{"url":"${mobileApplication.dataStoreApp.getServerLilium()}/#/entry/${
                        mobileApplication.dataStoreApp.readDataStoreKey<Int>("ENTRYID")
                    }/summary"}"""
                )
                customDialog.dismiss()
            }

            .setKoButton(
                getString(
                    R.string.cancel
                )
            ) {
                customDialog.dismiss()
            }.show()

    }

}

