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

import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPackagingSummaryBinding
import es.verdnatura.domain.ConstAndValues.ENTRYNUMBERIMAGES
import es.verdnatura.domain.ConstAndValues.ENTRYOBSERVATIONS
import es.verdnatura.domain.ConstAndValues.ENTRYTYPE
import es.verdnatura.domain.ConstAndValues.SUPPLIERNAME
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
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 kotlinx.coroutines.runBlocking

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

) : BaseFragment<FragmentPackagingSummaryBinding, 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>()
    private lateinit var departmentId: String

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

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

    override fun init() {

        binding.totalImages.text = mobileApplication.dataStoreApp.readDataStoreKey(ENTRYNUMBERIMAGES)
        binding.observations.text = mobileApplication.dataStoreApp.readDataStoreKey(ENTRYOBSERVATIONS)
        customDialogList = CustomDialogList(requireContext())
/*
        if (!departmentId.isEmpty()) {
            viewModel.workerGetFromHasMistake(
                getData(DEPARTMENTMISTAKEID).toInt()
            )
        }*/

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

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text = runBlocking {
            mobileApplication.dataStoreApp.readDataStoreKey<String>(ENTRYTYPE) + ":" + mobileApplication.dataStoreApp.readDataStoreKey<String>(
                SUPPLIERNAME
            )
        }

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconConfirm = ImageView(context)
        iconConfirm.setImageResource(R.drawable.check)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconConfirm.tooltipText = getString(R.string.confirmEntry)
        }

        listIcons.add(iconConfirm)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    when (item) {
                        iconConfirm.drawable -> {
                            // TODO()
                        }
                    }
                }

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

    }

    private fun setEvents() {

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

    }

    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)
                //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<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.workerMistake_Add(
                                 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) {
                }
            }

        }
        listWorker.add(WorkerFromMistake(0, "Añadir nuevo", "", false))
        listWorkerAuxiliary.clear()
        listWorkerAuxiliary.addAll(listWorker)
        listWorkerAuxiliary.add(WorkerFromMistake(0, "Añadir nuevo", "", false))

    }
}

