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

import android.app.AlertDialog
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentCollectionBinding
import es.verdnatura.domain.ConstAndValues.PRINTERNAME
import es.verdnatura.domain.ConstAndValues.SECTORFK
import es.verdnatura.domain.ConstAndValues.VERTICKET
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnMistakeClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPackingClickListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.OnQuantityClickListener
import es.verdnatura.presentation.common.OnSaleClickListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.collection.adapter.SaleAdapter
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO

class CollectionShowTicketFragment(
    var collection: CollectionVO = CollectionVO(0), var type: String = ""
) : BaseFragment<FragmentCollectionBinding, CollectionViewModel>(CollectionViewModel::class) {

    private var sales: List<SaleVO> = listOf()
    private var saleAdapter: SaleAdapter? = null
    private var lm: LinearLayoutManager? = null
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private lateinit var customDialog: CustomDialog
    private var tickets: ArrayList<String> = ArrayList()

    private var lastScanned: Int = 0
    private var buttonPushedGetCollection = false

    companion object {
        fun newInstance(collection: CollectionVO, type: String) =
            CollectionShowTicketFragment(collection, type)
    }

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

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

    override fun onCreate(savedInstanceState: Bundle?) {

        if (collection.tickets.isEmpty()) {
            viewModel.getSales(collection.collectionFk, print = "0", type)
        }

        super.onCreate(savedInstanceState)
    }

    override fun init() {
        customDialog = CustomDialog(requireContext())

        setEvents()
        setToolBarIcon()
        binding.mainToolbar.toolbarSubtitle.visibility = VISIBLE

        if (collection.tickets.isNotEmpty()) {
            createCollectionList()
        }

        super.init()
    }

    private fun setToolBarIcon() {
        binding.mainToolbar.toolbarSubtitle.visibility = VISIBLE
        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconPrint = ImageView(context)
        val iconViewCollection = ImageView(context)

        iconViewCollection.setImageResource(R.drawable.ic_collection)
        iconPrint.setImageResource(R.drawable.ic_print_black_24dp)
        iconPrint.tooltipText = getTooltip(R.drawable.ic_print_black_24dp)

        listIcons.add(iconPrint)
        listIcons.add(iconViewCollection)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    when (item) {
                        iconPrint.drawable -> print()
                        iconViewCollection.drawable -> getCollection()
                    }
                }

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

    private fun getCollection() {

        if (!buttonPushedGetCollection) {

            viewModel.collectionGetId(
                collection.collectionFk,
                mobileApplication.dataStoreApp.readDataStoreKey(SECTORFK),
                print = "0",
                type
            )
            buttonPushedGetCollection = true
        } else {
            viewModel.getSales(
                lastScanned, print = "0", type

            )
            buttonPushedGetCollection = false
        }
        lastScanned = collection.collectionFk
    }

    private fun print() {

        //tarea#4672
        var isTicket = false
        for (t in collection.tickets) {
            if (t.ticketFk.toInt() == (collection.collectionFk)) {
                isTicket = true
            }
        }
        if (isTicket) {
            val builder = AlertDialog.Builder(context)
            builder.setTitle(getString(R.string.selectLabeltoPrint))
            val labelCount = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
            builder.setItems(labelCount) { dialog, which ->
                viewModel.collectionStickerPrint(
                    collectionFk = collection.collectionFk, labelCount = (which + 1)
                )
            }
            val dialog = builder.create()
            dialog.show()
        } else {
            viewModel.collectionStickerPrint(

                collectionFk = collection.collectionFk, labelCount = null
            )

        }

    }

    private fun setEvents() {

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

        binding.scanInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {//ID=0 ACTION_NEXT  ID=5 ACTION_UNESPECEFIED)
                if (!binding.scanInput.text.toString().isNullOrEmpty()) {
                    buttonPushedGetCollection = false
                    try {
                        viewModel.getSales(
                            collectionFk = itemScanValue(
                                binding.scanInput.text.toString(),   arrayOf("ticket","saleGroup"), "id"
                            ).toString().toInt(),
                            print = "0",
                            source = type
                        )

                      println("qrTest2")

                      /*  viewModel.getSales(
                            binding.scanInput.text.toString().toInt(), print = "0", type
                        )*/
                    } catch (ex: Exception) {
                        getString(R.string.scanLabelTicket).toast(requireContext())
                    }

                }
                binding.scanInput.setText("")
                hideKeyboards()

                return@setOnEditorActionListener true
            }
            true
        }

        hideKeyboards()


        binding.collectionSwipe.setOnRefreshListener {

            binding.collectionSwipe.isRefreshing = false
            viewModel.getSales(
                collection.collectionFk, print = "0", type
            )
            binding.collectionSwipe.isRefreshing = false

        }
    }

    private fun hideKeyboards() {
        try {
            requireActivity().hideKeyboard()
        } catch (e: Exception) {
        }
    }

    override fun observeViewModel() {
        with(viewModel) {

            collectionTicketList.observe(viewLifecycleOwner, Observer {

                if (!it.isError) {
                    if (it.tickets.isNotEmpty()) {
                        collection = it
                        createCollectionList()

                    } else {
                        getString(R.string.collectionNoTicketsError).toast(requireContext())
                        ma.onMyBackPressed()

                    }
                } else {
                    ma.messageWithSound(it.errorMessage, it.isError, false)
                    if (activity != null) ma.onMyBackPressed()

                }

            })

            responsePrint.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    ma.messageWithSound(
                        it.errorMessage, it.isError, true
                    )
                } else {
                    (getString(R.string.Imprimiendo) + mobileApplication.dataStoreApp.readDataStoreKey<String>(
                        PRINTERNAME
                    )).toast(requireContext())
                }

            })
        }
    }

    private fun createCollectionList() {

        binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()
        val salesList: ArrayList<SaleVO> = ArrayList()
        tickets = ArrayList()
        var observations = ""
        collection.tickets.forEach { ticket ->
            ticket.sales.forEach { saleVO ->
                if (type == VERTICKET) {
                    salesList.add(saleVO)
                    if (tickets.firstOrNull { it == saleVO.ticketFk }.isNullOrEmpty()) tickets.add(
                        saleVO.ticketFk
                    )

                }

                observations =
                    observations.takeIf { !it.isNullOrBlank() }?.plus(" ${ticket.observations}")
                        ?: ""

            }
        }
        sales = salesList.sortedWith(compareBy({ it.saleOrder }))
        /*salesList.sortedWith(compareBy<SaleVO> { it.isPrepared == "0" }
            .thenBy { it.isControlled == "0" }*/

        saleAdapter =
            SaleAdapter(sales, pasillerosItemClickListener!!, object : OnQuantityClickListener {

                override fun onQuantityClick(sale: SaleVO) {
                }
            }, object : OnSaleClickListener {
                override fun onSaleClick(sale: SaleVO) {
                }

            }, object : OnMistakeClickListener {
                override fun onMistakeClickListener(sale: SaleVO) {
                }
            }, object : OnPackingClickListener {
                override fun onPackingClick(sale: SaleVO) {
                }

            })

        lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.fragmentSacadorCollections.adapter = saleAdapter
        binding.fragmentSacadorCollections.layoutManager = lm
        setTotalLines()
        setPosition()
        printObservations(observations)
        binding.scanInput.requestFocus()
    }

    private fun setPosition() {
        val firstIndex =
            sales.indexOfFirst { it.isPreviousPrepared == "0" && (it.isPrepared == "0" || it.isControlled == "0") }
        lm!!.scrollToPositionWithOffset(firstIndex, 0)
    }

    private fun printObservations(observations: String) {
        if (observations.trim().isNotEmpty()) {
            customDialog.setTitle(getString(R.string.observations)).setDescription(observations)
                .setOkButton(getString(R.string.accept)) {
                    customDialog.hide()
                    customDialog.dismiss()
                }.show()
        }
    }

    private fun setTotalLines() {
        var totalMark = 0
        sales.forEach {

            if (it.isControlled == "1") totalMark += 1
        }
        binding.mainToolbar.toolbarTitle.text = collection.collectionFk.toString()
        binding.mainToolbar.toolbarSubtitle.text = "" + totalMark + "/" + sales.size
        if (totalMark == sales.size) {
            getString(R.string.Coleccióncompleta).toast(this.context, Toast.LENGTH_SHORT)

        }
    }

}
