package es.verdnatura.presentation.view.feature.delivery.fragments

import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentExpeditionLogDeliveryBinding
import es.verdnatura.domain.toInt
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.view.feature.delivery.adapters.ExpeditionLogAdapter
import es.verdnatura.presentation.view.feature.delivery.model.ExpeditionInfoLog
import es.verdnatura.presentation.view.feature.delivery.model.ExpeditionSalix
import es.verdnatura.presentation.view.feature.delivery.model.Expeditions
import es.verdnatura.presentation.view.feature.delivery.model.RouteDelivery
import es.verdnatura.presentation.view.feature.delivery.viewmodels.DeliveryViewModel

class LogExpeditionFragment(
    var title: String = ""
) : BaseFragment<FragmentExpeditionLogDeliveryBinding, DeliveryViewModel>(
    DeliveryViewModel::class
) {

    private var adapter: ExpeditionLogAdapter? = null
    private var originalItem: Int = 0

    companion object {
        fun newInstance(title: String) = LogExpeditionFragment(title)
    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {

        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text = title
        binding.scanInput.requestFocus()
        setEvents()
        setToolBar()
        super.init()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setToolBar() {

        binding.mainToolbar.switchButton.tooltipText = getString(R.string.expeditionMarkFound)

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconDelivery = ImageView(context)
        iconDelivery.setImageResource(R.drawable.ic_delivery_truck)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconDelivery.tooltipText = getTooltip(R.drawable.ic_delivery_truck)
        }
        listIcons.add(iconDelivery)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {

                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconDelivery.drawable -> {
                            ma.openSummaryFragment(
                                binding.route.text.toString().toInt(), "ON_DELIVERY"
                            )
                        }
                    }
                }
            })

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

    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) {
                if (!binding.scanInput.text.isNullOrEmpty()) {

                    try {
                        viewModel.expeditionGetLog(binding.scanInput.toInt())
                        originalItem = binding.scanInput.toInt()
                        binding.mainToolbar.toolbarTitle.text =
                            """${getString(R.string.expedition)} ${binding.scanInput.text}"""
                    } catch (ex: Exception) {
                        getString(R.string.errorScanExpedition).toast(context, Toast.LENGTH_SHORT)
                    }
                }

                return@setOnEditorActionListener true
            }
            false
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun observeViewModel() {
        with(viewModel) {
            expeditionInfoList.observe(viewLifecycleOwner) {

                createList(it.list)
                setSwitchButon()
                viewModel.get_routesFromExpedition(originalItem)
            }
            routeInfoList.observe(viewLifecycleOwner) {

                if (it.list.isNotEmpty()) {
                    binding.mainToolbar.toolbarIcons.visibility = View.VISIBLE
                    binding.mainToolbar.switchButton.visibility = View.VISIBLE
                    setInfoText(it.list[0])
                } else {
                    binding.scanInput.setText("")
                    binding.routeLayout.visibility = View.GONE
                    binding.mainToolbar.toolbarIcons.visibility = View.GONE
                    binding.mainToolbar.switchButton.visibility = View.GONE
                }
            }
            responseStateAdd.observe(viewLifecycleOwner) {
                viewModel.expeditionGetLog(originalItem)
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setSwitchButon() {

        binding.mainToolbar.switchButton.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.mainToolbar.switchButton.tooltipText =
                if (isChecked) getString(R.string.expeditionMarkLost) else getString(R.string.expeditionMarkFound)

            if (isChecked) {
                viewModel.expeditionStateAddSalix(
                    Expeditions(
                        listOf(
                            ExpeditionSalix(expeditionFk = originalItem, stateCode = "FOUND")
                        )
                    )
                )
            } else {
                viewModel.expeditionStateAddSalix(
                    Expeditions(
                        listOf(
                            ExpeditionSalix(expeditionFk = originalItem, stateCode = "LOST")
                        )
                    )
                )
            }
        }

    }

    private fun setInfoText(routeDelivery: RouteDelivery) {
        binding.routeLayout.visibility = View.VISIBLE
        binding.mainToolbar.toolbarIcons.visibility = View.VISIBLE
        binding.route.text = routeDelivery.ticket.routeFk.toString()
        binding.agency.text = routeDelivery.ticket.route.agencyMode.agency.name ?: ""
        binding.scanInput.setText("")
    }

    private fun createList(list: List<ExpeditionInfoLog>) {
        adapter = ExpeditionLogAdapter(list)
        binding.itemexpeditionlogRecyclerview.adapter = adapter
        binding.itemexpeditionlogRecyclerview.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
    }

}