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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentGeneralBlackBinding
import es.verdnatura.domain.ConstAndValues
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnCollectionTicketSelectedListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.sacador.model.CollectionTicket

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class SectorCollectionReserveFragment(
    var title: String = "", var collectionFk: Int = 0, var hasToAdd: Boolean = false
) : BaseFragment<FragmentGeneralBlackBinding, PreSacadorViewModel>(
    PreSacadorViewModel::class
) {
    private var onCollectionSelectedListener: OnCollectionTicketSelectedListener? = null
    private lateinit var customDialogList: CustomDialogList
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var listSalesGroup: ArrayList<BarcodeVO> = ArrayList()
    private var listSaleGroupAdapter: BarcodeAdapter? = null
    private var onBack = false
    private var isReserved = false

    val listIcons: ArrayList<ImageView> = ArrayList()

    companion object {
        fun newInstance(title: String, collectionFk: Int, hasToAdd: Boolean) =
            SectorCollectionReserveFragment(title, collectionFk, hasToAdd)
    }

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

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnCollectionTicketSelectedListener) onCollectionSelectedListener = context
    }

    override fun onResume() {
        onBack = true
        super.onResume()
    }

    override fun init() {
        println("hasToAdd $hasToAdd")

        customDialogList = CustomDialogList(requireContext())
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text = title
        setEvents()
        setToolBar()

        println("reserve collec $collectionFk")
        println("reserve collec  onBack$onBack")

        if (!onBack) {
            println("check parkings  $collectionFk")
            checkParkingsToPicker()
        } else {
            if (onBack) {
                requireActivity().supportFragmentManager.popBackStack()
            } else {
                ma.onPasillerosItemClickListener(
                    PasillerosItemVO(title = R.string.titleprepickertest),
                    entryPoint = collectionFk.toString()
                )
            }
        }
        super.init()
    }

    private fun checkParkingsToPicker() {
        //Habrá que ver si tiene tickets ya asociados
        binding.mainToolbar.toolbarTitle.text = collectionFk.toString()
        viewModel.hasSalesReserved(collectionFk)
        //showDialogLinkTickets()

    }

    private fun setToolBar() {
        val listIcons: ArrayList<ImageView> = ArrayList()

        val iconReset = ImageView(context)
        iconReset.setImageResource(R.drawable.ic_delete_black_24dp)

        val iconParkingFrom = ImageView(context)
        iconParkingFrom.setImageResource(R.drawable.ic_mode_edit_black_24dp)

        iconParkingFrom.tooltipText = getString(R.string.editParking)
        iconReset.tooltipText = getString(R.string.resetParking)

        //listIcons.add(iconReset)
        // listIcons.add(iconParkingFrom)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {

                        iconReset.drawable -> {

                        }

                        iconParkingFrom.drawable -> {

                            showDialogLinkTickets()
                        }

                    }
                }

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

    private fun showDialogLinkTickets() {
        customDialogList.setOnDismissListener {
            // if (!isReserved) ma.onMyBackPressed()
        }
        customDialogList.setTitle(
            getString(R.string.tickets)
        )
        customDialogList.setDescription(

            getString(R.string.scanTicketsAssociate)
        ).setOkButton(getString(R.string.book)) {
            try {
                //Reservar colección
                if (!hasToAdd) {
                    viewModel.getReserveBySectorCollection(collectionFk)
                } else {
                    gotoPicker()
                }
            } catch (ex: Exception) {
                ma.messageWithSound(
                    message = getString(R.string.errorInput),
                    isError = true,
                    isPlayed = true,
                    isToasted = true
                )
            }

        }.setKoButton(getString(R.string.cancel)) {
            ma.hideKeyboard(customDialogList.getEditText())
            listSalesGroup = ArrayList()
            customDialogList.dismiss()

            // gotoPicker()
            /*ma.onMyBackPressed()*/
        }.setValue("").show()

        customDialogList.getEditText().requestFocus()
        ma.hideKeyboard(customDialogList.getEditText())

        customDialogList.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (customDialogList.getValue().isNotEmpty()) {

                    try {
                        customDialogList.setValue(
                            itemScanValue(
                                customDialogList.getValue(),
                                arrayOf("saleGroup"),
                                field = "id"
                            ).toString()
                        )
                        if (listSalesGroup.firstOrNull { it.code == customDialogList.getValue() } == null) {

                            viewModel.sectorCollectionSaleGroupAdd(
                                customDialogList.getValue().toInt(), collectionFk,
                            )
                        } else {
                            throw Exception(getString(R.string.ticketScanned))
                        }

                    } catch (e: Exception) {
                        ma.messageWithSound(
                            getString(R.string.errorInput),
                            isError = true,
                            isPlayed = true,
                            isToasted = true
                        )
                        //  listSalesGroup.removeAt(0)
                    }

                    //  listSaleGroupAdapter!!.notifyItemChanged(0)
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }

        listSaleGroupAdapter = BarcodeAdapter(
            listSalesGroup, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {

                }
            }, showDelete = false
        )
        customDialogList.getRecyclerView().adapter = listSaleGroupAdapter

        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

    }

    @SuppressLint("SetTextI18n")
    private fun setEvents() {

        //binding.scanInput.visibility = View.VISIBLE
        //binding.scanInput.setHint(getString(R.string.scanCollection))
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (binding.scanInput.text.toString().isNotEmpty()) {

                    try {
                        navigateToCollectionList(binding.scanInput.text.toString().toInt())

                    } catch (ex: Exception) {
                        ex.message!!.toast(requireContext())

                    }


                    binding.scanInput.setText("")
                    ma.hideKeyboard(binding.scanInput)
                }
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

    }

    private fun navigateToCollectionList(collectionFk: Int) {
        onCollectionSelectedListener!!.onCollectionSelected(
            CollectionTicket(collectionFk = collectionFk), ConstAndValues.PREPARED, true
        )
    }

    @SuppressLint("SetTextI18n")
    override fun observeViewModel() {

        with(viewModel) {

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

                    if (it.isError) {
                        listSalesGroup.removeAt(0)
                        ma.messageWithSound(
                            getString(R.string.errorTicketAdd) + it.errorMessage,
                            isError = true,
                            true,
                            isToasted = true
                        )

                    } else {
                        ma.messageWithSound(
                            message = "", isError = false, isPlayed = true, isToasted = false
                        )
                    }

                }
            }
            loadResponseHasSaleReserved.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

                    if (it > 0 && !hasToAdd) {
                        isReserved = true
                        gotoPicker()
                    } else {
                        showDialogLinkTickets()
                    }
                }
            }
            loadResponseSaleGropAdded.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    ma.messageWithSound(
                        message = "", isError = false, isPlayed = true, isToasted = false
                    )
                    listSalesGroup.add(BarcodeVO(code = it.toString()))
                    listSaleGroupAdapter!!.notifyItemInserted(listSalesGroup.size - 1)

                    if (hasToAdd) {
                        viewModel.getReserveBySaleGroup(it)
                    }
                }
            }
            loadResponseReserveSectorCollection.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

                    if (it.isError) {
                        ma.messageWithSound(
                            it.errorMessage, isError = true, true, isToasted = true
                        )

                    } else {
                        ma.messageWithSound(
                            message = "", isError = false, isPlayed = true, isToasted = false
                        )
                        //navigateToCollectionList(collectionFk = collectionFk)
                        gotoPicker()
                        //anar a SacadorFragmentNew

                    }

                }
            }
            loadResponseReserveSaleGroup.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

                    if (it.isError) {
                        ma.messageWithSound(
                            it.errorMessage, isError = true, true, isToasted = true
                        )

                    } else {
                        ma.messageWithSound(
                            message = "", isError = false, isPlayed = true, isToasted = false
                        )

                    }

                }
            }

        }
    }

    private fun gotoPicker() {
        if (::customDialogList.isInitialized) customDialogList.dismiss()

        ma.onPasillerosItemClickListener(
            PasillerosItemVO(title = R.string.preitempickertestMayus),
            entryPoint = collectionFk.toString()
        )
        // onBack = true
    }

}