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

import android.util.Base64.encodeToString
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import es.verdnatura.R
import es.verdnatura.databinding.FragmentShelvinglogBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.historicoshelvinglog.adapter.ShelvingLogAdapter
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import java.net.URLEncoder

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class shelvingLogFragment(
    var entryPoint: String = ""

) : BaseFragment<FragmentShelvinglogBinding, shelvingLogViewModel>(
    shelvingLogViewModel::class
) {
    // private lateinit var customDialogList: CustomDialogList
    private var adapter: ShelvingLogAdapter? = null
    private var itemScan = ""

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

    private lateinit var customDialog: CustomDialog

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

    override fun init() {

        customDialog = CustomDialog(requireContext())
        // customDialogList = CustomDialogList(requireContext())
        binding.linearHeader.visibility=View.GONE
        setEvents()
        setToolBar(getString(R.string.shelvingLog))
        super.init()

    }

    private fun setToolBar(title: String) {
        binding.mainToolbar.toolbarTitle.text = title


    }

    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()) {
                    shelvingLog_get(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 shelvingLog_get(vShelvingFK: String) {
        binding.splashProgress.visibility = View.VISIBLE
        // viewModel.shelvingLog_get(getData(USER), getData(PASSWORD),vShelvingFK)
        viewModel.Shelvings(getData(TOKEN), setFilter(vShelvingFK))

    }

    private fun setFilter(vShlevingFK: String): String {

        return "{\"where\": {\"code\": \"$vShlevingFK\"}}"

    }


    override fun observeViewModel() {
        with(viewModel) {

            loadShelvingLogList.observe(viewLifecycleOwner, Observer { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.GONE
                    adapter = ShelvingLogAdapter(it.list)
                    binding.itemshelvinglogRecyclerview.adapter = adapter
                    binding.itemshelvinglogRecyclerview.layoutManager =
                        LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
                    setToolBar(getString(R.string.shelvingLog) + ":" + itemScan)

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

                        if (it.list.get(0).isError) {
                            customDialog.setTitle(getString(R.string.error))
                                .setDescription(it.list.get(0).errorMessage)
                                .setOkButton(getString(R.string.close)) {
                                    customDialog.dismiss()
                                }.show()
                        }
                    }


                }
            })

            loadShelvingLogSalixList.observe(viewLifecycleOwner, Observer { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.GONE
                    //adapter = ShelvingLogAdapter(it.list)
                    binding.itemshelvinglogRecyclerview.adapter = adapter
                    binding.itemshelvinglogRecyclerview.layoutManager =
                        LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
                    setToolBar(getString(R.string.shelvingLog) + ":" + itemScan)

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

                        if (it.list.get(0).isError == true) {
                            it.list.get(0).errorMessage?.let { it1 ->
                                customDialog.setTitle(getString(R.string.error))
                                    .setDescription(it1)
                                    .setOkButton(getString(R.string.close)) {
                                        customDialog.dismiss()
                                    }.show()
                            }
                        } else {

                            var itemId= it.list[0].id
                            //val entrypoint = mutableMapOf("entryPoint" to itemScan, "web" to "https://test-salix.verdnatura.es/#!/shelving/$itemId/log")
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(
                                    title = getString(R.string.titleWebViewer),
                                ), entryPoint =  Gson().toJson(mutableMapOf("entryPoint" to itemId, "web" to "https://salix.verdnatura.es/#!/shelving/$itemId/log"))
                            )
                        }
                    }


                }
            })


        }
    }


}
