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

import android.app.AlertDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.view.View.VISIBLE
import androidx.appcompat.widget.TooltipCompat.setTooltipText
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.MobileApplication
import es.verdnatura.R
import es.verdnatura.databinding.FragmentAjustesBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnAjustesItemClickListener
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.feature.ajustes.adapter.AjustesAdapter
import es.verdnatura.presentation.view.feature.ajustes.model.AjustesItemVO
import es.verdnatura.presentation.view.feature.ajustes.model.Printers
import es.verdnatura.presentation.view.feature.ajustes.model.SectorItemVO
import es.verdnatura.presentation.view.feature.ajustes.model.Train
import es.verdnatura.presentation.view.feature.articulo.model.ItemPackingType
import es.verdnatura.presentation.view.feature.login.fragment.LoginViewModel
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO

class AjustesFragment :
    BaseFragment<FragmentAjustesBinding, AjustesViewModel>(AjustesViewModel::class) {

    private lateinit var customDialog: CustomDialog
    private lateinit var customDialogInput: CustomDialogInput
    private var sectorListVO: List<SectorItemVO> = listOf()
    private var printersList: List<Printers> = listOf()
    private var trainsList: List<Train> = listOf()
    private var prefs: SharedPreferences? = null
    private var ajustesAdapter: AjustesAdapter? = null
    private var isWorkerAllowed: Boolean = false
    private var itemPackingList: List<ItemPackingType> = listOf()
    private var messagePrinter: String? = null
    private lateinit var loginViewModel : LoginViewModel

    //añadido
    private var wagonList: List<String> = listOf()
    private var tagsList: List<String> = listOf()

    companion object {
        fun newInstance() = AjustesFragment()
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        prefs = requireActivity().getSharedPreferences(PREFS_USER, 0)
        customDialog = CustomDialog(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        super.onCreate(savedInstanceState)

    }

    override fun init() {

        binding.mainToolbar.toolbarTitle.text = getString(R.string.settings)
        binding.splashProgress.visibility = VISIBLE
        hideBackButton(binding.mainToolbar)
        viewModel.worker_isF11Allowed()

        binding.userText.text = mobileApplication.userName
        val versionName = requireActivity().packageManager.getPackageInfo(
            requireActivity().packageName,
            0
        ).versionName!!
        binding.itemVersion.text = versionName
        binding.androididText.text = getData(ANDROID_ID)

        // Tarea 4815
        binding.serialNumber.text = mobileApplication.serialNumber

        binding.txtserver.setText(getData(getString(R.string.baseurl)))
        super.init()

        setEvents()

    }

    fun setEvents() {
        binding.androididText.setOnClickListener { copyanddrag(binding.androididText.text.toString()) }
        binding.androididText.setOnLongClickListener { copyanddrag(binding.androididText.text.toString()) }
        binding.serialText.setOnLongClickListener {
            customDialogInput.setTitle(getString(R.string.serialNumberDescrip))
                .setDescription(getString(R.string.serialNumber))
                .setOkButton(getString(R.string.save)) {
                    saveData("SERIALNUMBER", customDialogInput.getValue())
                    binding.serialNumber.text = customDialogInput.getValue()
                    ma.hideKeyboard()
                    customDialogInput.dismiss()
                }.setKoButton(getString(R.string.cancel)) {
                    customDialogInput.dismiss()
                }
                .show()
            customDialogInput.setFocusText()
            true
        }

    }

    override fun observeViewModel() {
        with(viewModel) {

            ajustesAdapter = AjustesAdapter(ajustesitem, object : OnAjustesItemClickListener {
                override fun onAjustesItemClickListener(item: AjustesItemVO) {

                    if (item.action) {

                        if (item.id == 0) {
                            binding.splashProgress.visibility = VISIBLE
                            viewModel.getSectorsSalix()
                        } else if (item.id == 5) {
                            requireActivity().onBackPressed()
                        } else if (item.id == 1) {
                            //Tarea 4351 quitar parte de mostrar los carros y quitar del layout el ">" del final

                            ma.messageWithSound(
                                getString(R.string.managerWagon),
                                true,
                                true,
                                "Información",
                                false
                            )

                        } else if (item.id == 2) {
                            messagePrinter = getString(R.string.Selecccionaimpresoara)
                            viewModel.printer_get()

                        } else if (item.id == 3) {
                            val listTagsType: ArrayList<String> = ArrayList()
                            listTagsType.add(getString(R.string.stickers))
                            tagsList = listTagsType
                            val array = arrayOfNulls<String>(listTagsType.size)
                            showItemPickerType(array = listTagsType.toArray(array))
                        } else if (item.id == 4) {
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(
                                    title = getString(R.string.titleUserControlVehicle)
                                ), mobileApplication.userId.toString()
                            )

                        } else if (item.id == 6) {
                            binding.splashProgress.visibility = VISIBLE
                            viewModel.train_get()
                        } else if (item.id == 7) {
                            viewModel.getItemPackingTypeSalix()
                        }
                    }

                }
            })

            operatorGetItemPackingType.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, true)

                } else {
                    saveData(ITEMPACKING, it.response)
                }
                setSettings(isWorkerAllowed)
            }


            workerAllowedResponse.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, true)

                } else {
                    isWorkerAllowed = it.response.toBoolean()
                    loginViewModel= LoginViewModel(context as MobileApplication)
                    loginViewModel.operator_getDataSalix(mobileApplication.userId!!)
                    loginViewModel.workerOperator.observe(this@AjustesFragment) { it ->

                        if (!it.isError) {
                            saveDataOperator(it)
                        }else{
                            ma.messageWithSound(it.errorMessage, it.isError, true)
                        }
                    }


                }
                setSettings(isWorkerAllowed)

            }

            actionUpdate.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                ma.messageWithSound(
                    if (it.isError) it.errorMessage else {
                        getString(R.string.itemUpdated)
                    }, it.isError, false
                )

                binding.splashProgress.visibility = VISIBLE
                messagePrinter =
                    getString(R.string.Selecccionaimpresoara) + "\n" + getString(R.string.printerRemoved)
                viewModel.printer_get()

            }
            loadUpdatePacking.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.GONE
                }
            }


            actionUpdatePacking.observe(viewLifecycleOwner) {

                binding.splashProgress.visibility = View.GONE

                ma.messageWithSound(
                    if (it.isError) it.errorMessage else {
                        getString(R.string.itemUpdated)
                    }, it.isError, false
                )
            }


            isLoadingProgress.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = it

            }


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

            loadSectorList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.INVISIBLE
                    if (it.list.isNotEmpty() && 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()
                    } else {

                        if (it.list.size > 0) {
                            val listSectores: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listSectores.add(it.description)
                            }
                            val array = arrayOfNulls<String>(listSectores.size)
                            sectorListVO = it.list
                            showDialogSector(listSectores.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.sectors))
                                .setDescription(getString(R.string.Noexistessectores))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
            loadItemPackingList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.INVISIBLE
                    if (it.list.isNotEmpty() && 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()
                    } else {

                        if (it.list.size > 0) {
                            val listItemsPacking: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listItemsPacking.add(it.description)
                            }
                            val array = arrayOfNulls<String>(listItemsPacking.size)
                            itemPackingList = it.list
                            showDialog(listItemsPacking.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.settingsTitleItemPacking))
                                .setDescription(getString(R.string.NoItemPackingType))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
            loadPrintersList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.INVISIBLE
                    if (it.list.isNotEmpty() && 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()
                    } else {

                        if (it.list.size > 0) {
                            val listPrinters: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listPrinters.add(it.name)
                            }
                            val array = arrayOfNulls<String>(listPrinters.size)
                            printersList = it.list
                            showDialogPrinters(listPrinters.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.printers))
                                .setDescription(getString(R.string.Noprinters))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
            loadTrainList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.GONE
                    if (it.list.isNotEmpty() && 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()
                    } else {

                        if (it.list.size > 0) {
                            val listTrain: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listTrain.add(it.name)
                            }
                            val array = arrayOfNulls<String>(listTrain.size)
                            trainsList = it.list
                            showDialogTrains(listTrain.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.printers))
                                .setDescription(getString(R.string.Noprinters))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
        }
        super.observeViewModel()
    }

    private fun setSettings(actionIsAllowed: Boolean = false) {

        viewModel.inititializeDefaultAjusts(
            getData(SECTORDESCRIP),
            getDataInt(SECTORFK),
            getDataInt(WAREHOUSEFK),
            getData(NUMBEROFWAGONS),
            getDataInt(PRINTERFK),
            getData(PRINTERNAME),
            getData(TRAINNAME),
            getData(ITEMPACKING),
            actionIsAllowed = actionIsAllowed

        )
    }

    private fun showDialogPrinters(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)

        builder.setTitle(messagePrinter)

        // builder.setMessage("La impresora que tenía se ha eliminado ")
        builder.setItems(array) { _, which ->
            val selected = array[which]
            printersList.forEach {
                if (it.name.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(PRINTERNAME, it.name)
                    editor.putInt(PRINTERFK, it.id!!)
                    editor.apply()

                    viewModel.ajustesitem.get(2).selected = it.name
                    viewModel.worker_updateOperatorSalix(
                        "printer",
                        mobileApplication.userId!!,
                        getDataInt(SECTORFK),
                        it.id!!
                    )
                    ajustesAdapter!!.notifyDataSetChanged()
                    ajustesAdapter

                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialogTrains(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.selectTrain))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            trainsList.forEach {
                if (it.name.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(TRAINNAME, it.name)
                    editor.putInt(TRAINFK, it.id!!)
                    editor.apply()

                    viewModel.ajustesitem[3].selected = it.name
                    binding.splashProgress.visibility = VISIBLE
                    viewModel.operator_updateTrain(
                        it.id!!
                    )
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialogSector(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.Seleccionaunsector))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            sectorListVO.forEach {
                if (it.description.equals(selected)) {

                    //borra la impresora
                    viewModel.ajustesitem.get(2).selected = getString(R.string.noprinter)
                    saveData(PRINTERNAME, getString(R.string.noprinter))
                    saveDataInt(PRINTERFK, -1)

                    val editor = prefs!!.edit()
                    editor.putString(SECTORDESCRIP, it.description)
                    editor.putInt(SECTORFK, it.id)
                    it.warehouseFk?.let { it1 -> editor.putInt(WAREHOUSEFK, it1) }
                    editor.apply()

                    viewModel.ajustesitem.get(0).sectorFk = it.id
                    viewModel.ajustesitem.get(0).warehouse = it.warehouseFk
                    viewModel.ajustesitem.get(0).selected = it.description

                    viewModel.worker_updateOperatorSalix(
                        "sector",
                        mobileApplication.userId!!,
                        it.id,
                        null
                    )

                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialog(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)

        builder.setTitle(getString(R.string.settingsTitleItemPacking))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            itemPackingList.forEach {
                if (it.description.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(ITEMPACKING, it.description)
                    editor.apply()
                    viewModel.ajustesitem[4].selected = it.description
                    viewModel.operator_updateItemPackingType(
                        it.code
                    )
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialogCarros(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)
        builder.setTitle(getString(R.string.Seleccionauncarro))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            wagonList.forEach {
                if (it.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putInt(WAGON, it.toInt())
                    editor.apply()
                    viewModel.ajustesitem.get(1).selected = it
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }
        }

        val dialog = builder.create()
        dialog.show()
    }

    private fun showItemPickerType(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.typeTags))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            tagsList.forEach {
                if (it.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(TAGSTYPE, it)
                    editor.apply()

                    viewModel.ajustesitem.get(3).selected = it
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }


        }

        val dialog = builder.create()
        dialog.show()
    }


    private fun copyanddrag(string: String): Boolean {
        val clipboard = getActivity()?.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        val clip: ClipData = ClipData.newPlainText(getString(R.string.androidid), string)
        clipboard.setPrimaryClip(clip)
        setTooltipText(binding.androididText, getString(R.string.copied))
        return false

    }

}
