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

import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentItemdayofsaleCardBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.diadeventa.adapter.DayOfSaleAdapter
import es.verdnatura.presentation.view.feature.main.activity.MainActivity


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class DayOfSaleFragment(
    var entryPoint: String = ""
                       ) : BaseFragment<FragmentItemdayofsaleCardBinding, DayOfSaleViewModel>(DayOfSaleViewModel::class) {

    private lateinit var customDialogList: CustomDialogList
    private lateinit var customDialog: CustomDialog
    private var adapter: DayOfSaleAdapter? = null
    private var itemScan = ""

    companion object {
        fun newInstance(entryPoint: String) = DayOfSaleFragment(entryPoint)
    }


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

    override fun init() {

        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        setEvents()
        setToolBar(entryPoint)
        super.init()

    }

    private fun setToolBar(title: String) {
        binding.mainToolbar.toolbarTitle.text = title
        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconParking = ImageView(context)
        iconParking.setImageResource(R.drawable.ic_local_parking_black_24dp)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconParking.tooltipText = getTooltip(R.drawable.ic_local_parking_black_24dp)
        }

        listIcons.add(iconParking)

        binding.mainToolbar.toolbarIcons.adapter = ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
            override fun onOptionsItemSelected(item: Drawable) {

                if (item == iconParking.drawable) {
                    showParking()

                }


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

    }

    private fun setEvents() {
        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!binding.scanInput.text.toString().isNullOrEmpty()) {
                        getItemsSaleDate(binding.scanInput.text.toString())

                    itemScan = binding.scanInput.text.toString()
                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }


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

    }




    private fun getItemsSaleDate(vShelvingFK: String) {
        binding.splashProgress.visibility = View.VISIBLE
        viewModel.itemShelving_getSaleDate(getData(USER), getData(PASSWORD),vShelvingFK)

    }


    override fun observeViewModel() {
        with(viewModel) {

         loadItemShelvingSaleDateList.observe(viewLifecycleOwner, Observer{ event ->
                    event.getContentIfNotHandled().notNull {
                        binding.splashProgress.visibility = View.GONE
                        adapter = DayOfSaleAdapter(it.list)

                        binding.itemexpeditionstateRecyclerview.adapter = adapter
                        binding.itemexpeditionstateRecyclerview.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

               if  (it.list.isEmpty()){
                   customDialog.setTitle(getString(R.string.noResults))
                       .setDescription(getString(R.string.wagoonNoSaleToday))
                       .setOkButton(getString(R.string.close)) {
                           customDialog.dismiss()
                       }.show()
                }else{

                        if (it.list.get(0).isError){
                            ma.messageWithSound(it.list.get(0).errorMessage,it.list.get(0).isError,isPlayed = false)
                            /*customDialog.setTitle(getString(R.string.error))
                                .setDescription(it.list.get(0).errorMessage)
                                .setOkButton(getString(R.string.close)) {
                                    customDialog.dismiss()
                                }.show()*/
                        }
                }

                    }
                })
            response.observe(viewLifecycleOwner, Observer {
                if (it.isError){

                    binding.splashProgress.visibility = View.GONE
                    ma.messageWithSound(it.errorMessage,true,false)
                    /*customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage).setOkButton(getString(R.string.close)){
                        customDialog.dismiss()
                    }.show()*/

                }else{

                    customDialog.setTitle(getString(R.string.info)).setDescription(getString(R.string.parkingOk)).setOkButton(getString(R.string.close)) {
                        customDialog.dismiss()
                    }.show()

                }


            })


        }
    }

    private fun showParking() {

        customDialogList.setTitle(getString(R.string.showParking))
            .setOkButton(getString(R.string.close)) {

                ma.hideKeyboard(customDialogList.getEditText())

                customDialogList.dismiss()

            }.setValue("").show()


        customDialogList.getEditText().requestFocus()
        ma.hideKeyboard(customDialogList.getEditText())

        customDialogList.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5 || actionId == 6) {
                if (customDialogList.getValue().isNotEmpty()) {
                    parking(customDialogList.getValue())
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }


    }

    fun parking(parking:String){
        viewModel.parking(
            usuario = getData(USER),
            password = getData(PASSWORD),
            parking = parking,
            scanItem = itemScan)
        customDialogList.dismiss()

    }


}


