package es.verdnatura.presentation.view.feature.workermistake.adapter

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentWorkermistakeBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.common.onMistakeWorkerClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.inventario.fragment.InventaryViewModel
import es.verdnatura.presentation.view.feature.inventario.fragment.SearchDepartmentModel
import es.verdnatura.presentation.view.feature.workermistake.model.DepartmentMistake
import es.verdnatura.presentation.view.feature.workermistake.model.MistakeWorkerType
import es.verdnatura.presentation.view.feature.workermistake.model.WorkerFromMistake
import ir.mirrajabi.searchdialog.SimpleSearchDialogCompat

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

) : BaseFragment<FragmentWorkermistakeBinding, InventaryViewModel>(
    InventaryViewModel::class
) {

    private var adapterworker: WorkermistakeAdapter? = null

    private lateinit var customDialogInput: CustomDialogInput


    private var listWorker: MutableList<WorkerFromMistake> = ArrayList()
    private var listWorkerAuxiliary: MutableList<WorkerFromMistake> = ArrayList()
    private lateinit var customDialog: CustomDialog
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var layoutManager: LinearLayoutManager? = null

    // private var firstVisiblePosition = 0
    private lateinit var customDialogList: CustomDialogList
    private var listMistakes: ArrayList<BarcodeVO> = ArrayList()
    private var listMistakesAdapter: BarcodeAdapter? = null
    private var workerMistakeName: WorkerFromMistake? = null


    private val departments = ArrayList<SearchDepartmentModel>()
    private lateinit var departmentId: String

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

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

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

    override fun onCreate(savedInstanceState: Bundle?) {


        var working_in_test = false //sergio:No posar a true fins que Salix puje versió 8.3

        if (!working_in_test) {
            viewModel.department_getHasMistake(
                usuario = getData(USER),
                password = getData(PASSWORD)
            )
        } else {
            viewModel.department_getHasMistakeSalix(getData(TOKEN))
        }

        super.onCreate(savedInstanceState)
    }


    override fun init() {


        binding.filterDepartment.setText(getData(DEPARTMENTMISTAKE))
        binding.splashProgress.visibility = View.VISIBLE
        departmentId = getData(DEPARTMENTMISTAKEID)

        customDialogList = CustomDialogList(requireContext())

        if (!departmentId.isEmpty()) {
            viewModel.worker_getFromHasMistake(
                getData(USER),
                getData(PASSWORD),
                getData(DEPARTMENTMISTAKEID)
            )
        }

        binding.filterDepartment.setOnClickListener {
            SimpleSearchDialogCompat(context,
                getString(R.string.departamentos),
                getString(R.string.escribirparteNombre),
                null,
                departments,
                { baseSearchDialogCompat, nombre, position ->

                    binding.filterDepartment.setText((nombre.title))

                    saveData(DEPARTMENTMISTAKE, nombre.getDepartmentName())
                    saveData(DEPARTMENTMISTAKEID, nombre.getDepartmentId())
                    viewModel.worker_getFromHasMistake(
                        getData(USER),
                        getData(PASSWORD),
                        nombre.getDepartmentId()
                    )
                    binding.splashProgress.visibility = View.VISIBLE
                    binding.filterItemFk.isEnabled = true
                    baseSearchDialogCompat.dismiss()
                }).show()
        }


        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        ma.hideBottomNavigation(View.GONE)
        binding.splashProgress.visibility = View.VISIBLE
        setToolBar()
        setEvents()
        super.init()
    }

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text = entryPoint

    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }
        if (binding.filterDepartment.text.isNullOrEmpty()) {
            binding.filterItemFk.isEnabled = false
        }
        binding.filterItemFk.addTextChangedListener { filter() }

    }

    private fun filter() {

        if (!listWorker.isNullOrEmpty()) {
            listWorker.clear()
            listWorker.addAll(listWorkerAuxiliary.filter {
                it.firstName.uppercase().contains(
                    binding.filterItemFk.text.toString().uppercase()
                ) || it.lastName.uppercase()
                    .contains(binding.filterItemFk.text.toString().uppercase())
            } as MutableList<WorkerFromMistake>)
            adapterworker!!.notifyDataSetChanged()
        }

    }


    /*  override fun onPause() {
          super.onPause()
          firstVisiblePosition = layoutManager?.findFirstVisibleItemPosition() ?: 0
      }*/

    /* override fun onResume() {
         super.onResume()
         if (binding.workermistakeRecyclerview.layoutManager  != null){
             if (firstVisiblePosition <= listInvetory.size){
                 binding.workermistakeRecyclerview.layoutManager!!.scrollToPosition(firstVisiblePosition)
             }
         }
     }*/

    override fun observeViewModel() {
        with(viewModel) {


            mistakeDepartmentList.observe(viewLifecycleOwner, {
                binding.splashProgress.visibility = View.GONE
                createDepartmentList(it.list)

            })
            workerFromMistakeList.observe(viewLifecycleOwner, {
                binding.splashProgress.visibility = View.GONE
                createWorkerList(it.list)

                adapterworker =
                    WorkermistakeAdapter(listWorker, object : onMistakeWorkerClickListener {

                        override fun onMistakeWorkerClickListener(item: WorkerFromMistake) {
                            viewModel.workerMistakeType_get(
                                usuario = getData(USER),
                                password = getData(PASSWORD)
                            )
                            workerMistakeName =
                                WorkerFromMistake(item.id, item.firstName, item.lastName, true, "")


                        }
                    })
                binding.workermistakeRecyclerview.adapter = adapterworker
                layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
                binding.workermistakeRecyclerview.layoutManager = layoutManager

            })

            mistakeWorkerList.observe(viewLifecycleOwner, {
                binding.splashProgress.visibility = View.GONE
                showMistakeList(it.list)
                //goBack = false

            })

            responseAddMistake.observe(viewLifecycleOwner, {


                ma.messageWithSound(
                    if (it.isError) {
                        if (it.codeError == 403) {
                            getString(R.string.userNotPermission)
                        } else {
                            it.errorMessage
                        }

                    } else {
                        getString(R.string.errorCauseRegistered)
                    }, it.isError, true, isToasted = true
                )

            })

            response.observe(viewLifecycleOwner, {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)

                }
            })
        }
    }


    private fun showMistakeList(list: List<MistakeWorkerType>) {
        binding.splashProgress.visibility = View.GONE
        listMistakes = ArrayList()
        list.forEach {
            listMistakes.add(BarcodeVO(code = it.description))
        }


        customDialogList.setTitle(getString(R.string.errorCause) + workerMistakeName!!.firstName)
            .setKoButton(
                getString(
                    R.string.cancel
                )
            ) {
                customDialogList.dismiss()
            }.hideDialog().show()


        listMistakesAdapter =
            BarcodeAdapter(listMistakes, object : OnBarcodeRowClickListener {
                override fun onBarcodeRowClickListener(item: BarcodeVO) {
                    list.forEach {
                        if (it.description == item.code) {
                            viewModel.workerMistake_Add(
                                usuario = getData(USER),
                                password = getData(PASSWORD),
                                vUserFk = workerMistakeName!!.id,
                                vTypeFk = it.code
                            )
                            // getString(R.string.errorRegistered).toast(requireContext())
                            customDialogList.dismiss()
                        }
                    }

                }
            }, showDelete = false)

        customDialogList.getRecyclerView().adapter = listMistakesAdapter

        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

    }


    private fun createDepartmentList(list: List<DepartmentMistake>) {
        departments.clear()
        list.forEach { department ->
            if (!department.isError) {
                try {
                    departments.add(SearchDepartmentModel(department.name, department.id))
                } catch (e: Exception) {
                }
            }
        }
    }

    private fun createWorkerList(list: List<WorkerFromMistake>) {
        listWorker.clear()

        list.forEach { worker ->

            if (!worker.isError) {
                try {
                    listWorker.add(worker)
                } catch (e: Exception) {
                }
            }

        }
        listWorkerAuxiliary.clear()
        listWorkerAuxiliary.addAll(listWorker)

    }
}

