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

import android.content.Intent
import android.graphics.drawable.Drawable
import android.text.InputType
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPackagingCountBinding
import es.verdnatura.domain.ConstAndValues.ENTRYID
import es.verdnatura.domain.ConstAndValues.SUPPLIERID
import es.verdnatura.domain.ConstAndValues.SUPPLIERNAME
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnEditSubQuantityListener
import es.verdnatura.presentation.common.OnImageTrashClickListener
import es.verdnatura.presentation.common.OnImageUpdateClickListener
import es.verdnatura.presentation.common.OnItemClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.feature.articulo.fragment.ImageViewActivity
import es.verdnatura.presentation.view.feature.packaging.adapter.ItemSupplierAdapter
import es.verdnatura.presentation.view.feature.packaging.model.ItemSupplier
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO

class PackagingCountFragment(
    var entryPoint: String = ""

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

    private var adapteritemsupplier: ItemSupplierAdapter? = null
    private lateinit var customDialogInput: CustomDialogInput
    private var listItemSupplier: MutableList<ItemSupplier> = ArrayList()
    private lateinit var customDialog: CustomDialog
    private var layoutManager: LinearLayoutManager? = null

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

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

    override fun init() {

        viewModel.getItemsPackaging(
            mobileApplication.dataStoreApp.readDataStoreKey(SUPPLIERID),
            mobileApplication.dataStoreApp.readDataStoreKey(ENTRYID)
        )
        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        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 iconNext = ImageView(context)
        iconNext.setImageResource(R.drawable.ic_chevron_right_black_24dp)
        iconNext.tooltipText = getString(R.string.entryNextObsers)
        listIcons.add(iconNext)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    when (item) {
                        iconNext.drawable -> {
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(title = R.string.titlePackagingObs),
                                getString(R.string.titlePackagingObs)
                            )
                        }

                    }

                }

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

    }

    private fun setEvents() {

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

    }

    override fun observeViewModel() {
        with(viewModel) {

            loadEntryAdd.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

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

                }
            }

            itemSupplierList.observe(viewLifecycleOwner) { iti ->
                adapteritemsupplier =
                    ItemSupplierAdapter(
                        iti.list.sortedBy { it.name },
                        object : OnImageUpdateClickListener {

                            override fun onImageUpdateClickListener(item: Any) {
                                showCustomDialog("quantity", item as ItemSupplier)

                            }

                        },
                        object : OnImageTrashClickListener {
                            override fun onImageTrashClickListener(item: Any) {
                                showCustomDialog("delete", item as ItemSupplier)
                            }

                        },
                        object : OnEditSubQuantityListener {
                            override fun onEditSubQuantityListener(item: Any, text: String) {
                                hideKeyboard()
                            }

                        },
                        object : OnItemClickListener {
                            override fun onItemClickListener(item: ItemSupplier) {
                                if (!item.url.isNullOrBlank()) {
                                    val i = Intent(activity, ImageViewActivity::class.java)
                                    i.putExtra(
                                        getString(R.string.url),
                                        "http:${item.url}/catalog/1600x900/${item.id}"
                                    )
                                    i.putExtra(getString(R.string.title), item.name)
                                    startActivity(i)
                                }
                            }
                        })
                binding.itemsupplierRecyclerview.adapter = adapteritemsupplier
                layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
                binding.itemsupplierRecyclerview.layoutManager = layoutManager

            }

        }
    }

    private fun showCustomDialog(action: String, item: ItemSupplier) {

        when (action) {
            "quantity" -> {
                customDialogInput.getEditText().setRawInputType(InputType.TYPE_CLASS_NUMBER)
                customDialogInput.setVisibilityPlusButtons(View.VISIBLE)
                customDialogInput.setTitle(getString(R.string.quantityReviewed))
                    .setDescription(getString(R.string.Indicanuevacantidad))
                    .setOkButton(getString(R.string.accept)) {
                        if (customDialogInput.getValue().isNotEmpty()) {
                            requireActivity().hideKeyboard()
                        }
                        viewModel.entryAddFromBuy(
                            mobileApplication.dataStoreApp.readDataStoreKey<Int>(ENTRYID),
                            item = item.id!!.toInt(),
                            item.printedStickers.plus(customDialogInput.getValue().toInt())
                        )

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



                customDialogInput.currentFocus
                customDialogInput.setFocusText()
            }

            "delete" -> {
                customDialog.setTitle(getString(R.string.deleteEntryReviewed))
                    .setDescription(getString(R.string.sure))
                    .setOkButton(
                        getString(
                            R.string.delete
                        )

                    ) {
                        customDialog.cancel()
                        customDialog.dismiss()

                        viewModel.entryAddFromBuy(
                            mobileApplication.dataStoreApp.readDataStoreKey<Int>("ENTRYID"),
                            item = item.id!!.toInt(),
                            printedStickers = 0
                        )
                    }

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

                    }
                    .show()
            }

        }

    }

}



