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

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.View.GONE
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.VERTICKET
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.collection.adapter.SaleAdapter
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.sacador.model.SaleVO

class CollectionShowTicketFragment(
    var collection: CollectionVO = CollectionVO(),
    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()


    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.collectionTicketGet(
                getData(USER),
                getData(PASSWORD),
                collection.collectionFk,
                getData(SECTORFK),
                type
            )
        }

        super.onCreate(savedInstanceState)
    }

    override fun init() {
        customDialog = CustomDialog(requireContext())
        //84ma.hideBottomNavigation(GONE)
        binding.splashProgress.visibility = VISIBLE
        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)
        iconPrint.setImageResource(R.drawable.ic_print_black_24dp)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconPrint.tooltipText = getTooltip(R.drawable.ic_print_black_24dp)

        }
        listIcons.add(iconPrint)

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

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

    private fun print() {

        if (ma.havePrinter() && ma.haveSector()) {
            viewModel.collectionStickerPrint(
                usuario = getData(USER),
                password = getData(PASSWORD),
                collectionFk = collection.collectionFk,
                sectorFk = getData(SECTORFK)

            )

            (getString(R.string.Imprimiendo) + getData(PRINTERNAME)).toast(requireContext())
        }else{

                ma.messageWithSound(getString(R.string.printerFault),isError = true,true,getString(R.string.error),false)

        }
    }
    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        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()) {
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.collectionTicketGet(
                        getData(USER),
                        getData(PASSWORD),
                        binding.scanInput.text.toString(),
                        getData(SECTORFK),
                        type
                    )


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

                return@setOnEditorActionListener true
            }
            true
        }

        hideKeyboards()


        binding.collectionSwipe.setOnRefreshListener {

            binding.collectionSwipe.isRefreshing = false
            binding.splashProgress.visibility = VISIBLE
            viewModel.collectionTicketGet(
                getData(USER),
                getData(PASSWORD),
                collection.collectionFk,
                getData(SECTORFK),
                type
            )
            binding.collectionSwipe.isRefreshing = false

        }
    }

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

    override fun observeViewModel() {
        with(viewModel) {

            binding.splashProgress.visibility = GONE
            collectionTicketList.observe(viewLifecycleOwner, Observer {

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


                    } else {
                        binding.mainToolbar.toolbarSubtitle.text = "0/0"
                    }
                } else {
                    ma.messageWithSound(it.errorMessage,it.isError,false)
                    if (activity != null) requireActivity().onBackPressed()

                }

            })
        }
    }


    private fun createCollectionList() {

        binding.mainToolbar.toolbarTitle.text = collection.collectionFk
        binding.splashProgress.visibility = View.GONE
        var 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 + " " + ticket.observations
            }
        }
        sales = salesList.sortedWith(compareBy({ it.saleOrder }))


        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()
        printObservations(observations)
        binding.scanInput.requestFocus()
    }


    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
        binding.mainToolbar.toolbarSubtitle.text =
            "" + totalMark + "/" + sales.size
        if (totalMark == sales.size) {
            getString(R.string.Coleccióncompleta).toast(this.context, Toast.LENGTH_SHORT)

        }
    }


}
