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

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentWorkermistakeBinding
import es.verdnatura.domain.ConstAndValues.DEPARTMENTMISTAKE
import es.verdnatura.domain.ConstAndValues.DEPARTMENTMISTAKEID
import es.verdnatura.domain.toast
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.adapter.WorkermistakeAdapter
import es.verdnatura.presentation.view.feature.workermistake.model.DepartmentMistake
import es.verdnatura.presentation.view.feature.workermistake.model.MistakeType
import es.verdnatura.presentation.view.feature.workermistake.model.WorkerFromMistake
import ir.mirrajabi.searchdialog.SimpleSearchDialogCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

@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 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>()

    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?) {
        viewModel.departmentGetHasMistake()
        super.onCreate(savedInstanceState)
    }

    override fun init() {

        runBlocking {
            binding.filterDepartment.text =
                mobileApplication.dataStoreApp.readDataStoreKey<String>("DEPARTMENTMISTAKE")
            var departmentId =    mobileApplication.dataStoreApp.readDataStoreKey<Int>("DEPARTMENTMISTAKEID")
            if (departmentId != 0) {
                viewModel.workerGetFromHasMistake(
                    departmentId!!
                )
            }
        }

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

                binding.filterDepartment.text = (nombre.title)
                lifecycleScope.launch(Dispatchers.IO) {
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        DEPARTMENTMISTAKE,
                        nombre.getDepartmentName()
                    )
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        DEPARTMENTMISTAKEID,
                        nombre.getDepartmentId()
                    )
                }

                viewModel.workerGetFromHasMistake(
                    nombre.getDepartmentId()
                )
                binding.filterItemFk.isEnabled = true
                baseSearchDialogCompat.dismiss()
            }.show()
        }
        customDialogInput = CustomDialogInput(requireContext())
        customDialog = CustomDialog(requireContext())
        ma.hideBottomNavigation(View.GONE)
        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 observeViewModel() {
        with(viewModel) {
            mistakeDepartmentList.observe(viewLifecycleOwner) {
                createDepartmentList(it.list)
            }
            workerFromMistakeList.observe(viewLifecycleOwner) {
                createWorkerList(it.list)
                adapterworker =
                    WorkermistakeAdapter(listWorker, object : onMistakeWorkerClickListener {
                        override fun onMistakeWorkerClickListener(item: WorkerFromMistake) {
                            viewModel.workerMistakeTypeGet(
                            )
                            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) {
                showMistakeList(it.list)
            }
        }
    }

    private fun showMistakeList(list: List<MistakeType>) {
        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.workerMistakeAdd(
                                vUserFk = workerMistakeName!!.id!!,
                                vTypeFk = it.code
                            )
                            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) {
                    e.message!!.toast(requireContext())
                }
            }
        }
    }

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

        list.forEach { worker ->
            if (!worker.isError) {
                try {
                    listWorker.add(worker)
                } catch (e: Exception) {
                    e.message!!.toast(requireContext())
                }
            }

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

    }
}

