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

import android.graphics.drawable.Drawable
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentExpeditionLogDeliveryBinding
import es.verdnatura.domain.toLong
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: Long = 0
    private var isScanned: Boolean = false

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

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

    override fun init() {

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

    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)
        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 {
            ma.onMyBackPressed()
        }

        binding.scanInput.setOnEditorActionListener { _, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == EditorInfo.IME_ACTION_NEXT) {
                if (!binding.scanInput.text.isNullOrEmpty()) {
                    isScanned =
                        event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER
                    try {
                        viewModel.expeditionGetLog(binding.scanInput.toLong())
                        originalItem = binding.scanInput.toLong()
                        binding.mainToolbar.toolbarTitle.text =
                            getString(
                                R.string.titleLogExpedition,
                                getString(R.string.expedition),
                                binding.scanInput.text
                            )
                    } catch (ex: Exception) {
                        getString(R.string.errorScanExpedition).toast(context, Toast.LENGTH_SHORT)
                    }
                }

                return@setOnEditorActionListener false
            }
            false
        }

    }

    override fun observeViewModel() {
        with(viewModel) {
            expeditionInfoList.observe(viewLifecycleOwner) {

                createList(it.list)
                setSwitchButon()
                viewModel.getRoutesFromExpedition(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
                }
                binding.scanInput.requestFocus()
            }
            responseStateAdd.observe(viewLifecycleOwner) {
                viewModel.expeditionGetLog(originalItem)
            }
        }
    }

    private fun setSwitchButon() {

        binding.mainToolbar.switchButton.setOnCheckedChangeListener { _, 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",
                                isScanned = if (isScanned) 1 else 0
                            )
                        )
                    )
                )
            } else {
                viewModel.expeditionStateAddSalix(
                    Expeditions(
                        listOf(
                            ExpeditionSalix(
                                expeditionFk = originalItem,
                                stateCode = "LOST",
                                isScanned = if (isScanned) 1 else 0
                            )
                        )
                    )
                )
            }
        }

    }

    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)
    }

}