package es.verdnatura.presentation.view.feature.sacador.fragment.showticket

import android.content.Context
import android.os.Bundle
import android.text.InputType.TYPE_CLASS_NUMBER
import android.util.Log.e
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentShowTicketBinding
import es.verdnatura.domain.ConstAndValues
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnCollectionSelectedListener
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.feature.sacador.adapter.TicketLastStateAdapter
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.sacador.model.TicketStateSalix

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ShowTicketFragment() :
    BaseFragment<FragmentShowTicketBinding, ShowTicketViewModel>(
        ShowTicketViewModel::class
    ) {
    private var menuOrigin: String? = null
    private var goBack: Boolean = false
    private var onCollectionSelectedListener: OnCollectionSelectedListener? = null
    override fun getLayoutId(): Int = R.layout.fragment_show_ticket
    private var type = ""
    private var adapter: TicketLastStateAdapter? = null

    constructor(menuOrigin: String) : this() {
        this.menuOrigin = menuOrigin
    }

    companion object {
        private const val ARG_MENU_ORIGIN = "menu_origin"

        fun newInstance(menuOrigin: String) = ShowTicketFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_MENU_ORIGIN, menuOrigin)
            }
        }
    }

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

    override fun init() {
        binding.scanInput.visibility = View.VISIBLE
        binding.mainToolbar.toolbarTitle.text = getString(R.string.verticket)
        ma.hideBottomNavigation(View.VISIBLE)
        if (menuOrigin == getString(R.string.main)) {
            hideBackButton(binding.mainToolbar)
        }
        setEvents()
        //Tarea 6531
        try {
            viewModel.myLastTickets(mobileApplication.userId!!)
        } catch (ex: Exception) {
            e("Crashlytics", ex.message.toString())
        }

        super.init()
    }

    override fun onPause() {
        goBack = true
        super.onPause()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        type = ConstAndValues.VERTICKET
        arguments?.let {
            menuOrigin = it.getString(ARG_MENU_ORIGIN)
        }
        super.onCreate(savedInstanceState)
    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }
        binding.sacadorSwipe.setOnRefreshListener {
            binding.sacadorSwipe.isRefreshing = true
            //Tarea 6531
            viewModel.myLastTickets(mobileApplication.userId!!)
            binding.sacadorSwipe.isRefreshing = false
        }

        binding.scanInput.requestFocus()
        binding.scanInput.setRawInputType(TYPE_CLASS_NUMBER)
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                goBack = false
                if (!binding.scanInput.text.isNullOrEmpty()) {

                    try {

                        viewModel.getSales(
                            collectionFk = itemScanValue(
                                binding.scanInput.text.toString(),
                                arrayOf("ticket", "saleGroup"),
                                "id"
                            ).toString().toInt(),
                            print = false,
                            source = type
                        )

                    } catch (ex: Exception) {

                        ma.messageWithSound(
                            getString(R.string.errorReviewItem),
                            true,
                            isPlayed = true,
                            isToasted = true
                        )
                    }
                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }
    }

    private fun createCollectionList(listTickets: List<TicketStateSalix>) {

        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = TicketLastStateAdapter(listTickets, onCollectionSelectedListener!!, type)
        binding.lastTicketsRecyclerview.layoutManager = lm
        binding.lastTicketsRecyclerview.adapter = adapter

    }

    override fun observeViewModel() {
        with(viewModel) {
            collectionTicketList.observe(viewLifecycleOwner) {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)
                } else {
                    if (!goBack) navigateToCollectionList(it)
                    goBack = false
                }

            }
            lastTicketList.observe(viewLifecycleOwner) {
                if (it.list.isNotEmpty()) {
                    createCollectionList(it.list)
                } else {
                    binding.txtLastTickets.visibility = View.INVISIBLE
                }
            }
        }

    }

    private fun navigateToCollectionList(collection: CollectionVO) {
        if (collection.collectionFk != 0) onCollectionSelectedListener?.onCollectionSelected(
            collection,
            ConstAndValues.VERTICKET
        )
    }

}

