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

import android.app.AlertDialog
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.InputType
import android.view.View
import android.view.View.GONE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import es.verdnatura.R
import es.verdnatura.databinding.FragmentItemCardBinding
import es.verdnatura.domain.ConstAndValues.BASEURLSALIX
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFK
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialogDynamicButtons
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogTwoButtons
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.adapter.ItemCardAdapter
import es.verdnatura.presentation.view.feature.articulo.model.AddressLoses
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.articulo.model.ItemCardRowVO
import es.verdnatura.presentation.view.feature.articulo.model.ItemCardVO
import es.verdnatura.presentation.view.feature.articulo.model.ItemPackingType
import es.verdnatura.presentation.view.feature.imageview.activity.ImageViewActivity
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO

class ItemCardFragment(
    var itemFk: String = ""
) : BaseFragment<FragmentItemCardBinding, ItemCardViewModel>(ItemCardViewModel::class),
    OnClickDynamic {

    private var urlLarge: String? = ""
    private var titleImage: String = ""
    private var user = ""
    private var password = ""
    private var warehouseFk: Int? = null
    private var adapter: ItemCardAdapter? = null
    private var barcodeAdapter: BarcodeAdapter? = null
    private var listItemsRow: ArrayList<ItemCardRowVO> = ArrayList()
    private var listBarcodes: ArrayList<BarcodeVO> = ArrayList()
    private var itemsPackingType: ArrayList<ItemPackingType> = ArrayList()
    private var quantityToDiscard = 0
    private var itemInfoG: ItemCardVO? = null

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

    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogList: CustomDialogList
    private lateinit var customDialogTwo: CustomDialogTwoButtons
    private lateinit var customDynamic: CustomDialogDynamicButtons

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

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {

        binding.itemcardLayout.visibility = GONE
        ma.hideBottomNavigation(GONE)
        binding.mainToolbar.toolbarTitle.text = getString(R.string.titleItemConsult)
        customDialogInput = CustomDialogInput(requireContext())
        customDialogList = CustomDialogList(requireContext())
        customDialogTwo = CustomDialogTwoButtons(requireContext())
        customDynamic = CustomDialogDynamicButtons(requireContext(), this)

        if (itemFk.isNotEmpty()) {
            getItemCard(itemFk)
        }
        setToolBar()
        setEvents()
        super.init()

    }

    private fun setToolBar() {

        binding.mainToolbar.toolbarIcons.visibility = GONE

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_autorenew_black_24dp)
        val iconHistory = ImageView(context)
        iconHistory.setImageResource(R.drawable.ic_history_black_24dp)
        val iconSalix = ImageView(context)
        iconSalix.setImageResource(R.drawable.ic_logo_salix)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconReload.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)
            iconHistory.tooltipText = getTooltip(R.drawable.ic_history_black_24dp)
            iconSalix.tooltipText = getTooltip(R.drawable.ic_logo_salix)
        }
        listIcons.add(iconSalix)
        listIcons.add(iconReload)
        listIcons.add(iconHistory)


        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {

                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconReload.drawable -> {
                            getItemCard(itemInfoG!!.id.toString())
                        }

                        iconHistory.drawable -> {

                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(title = getString(R.string.titleHistorical)),
                                itemInfoG!!.id.toString()
                            )

                        }

                        iconSalix.drawable -> {
                            binding.splashProgress.visibility = View.VISIBLE
                            val itemId = itemInfoG!!.id
                            val entryPoint = Gson().toJson(
                                mutableMapOf(
                                    "entryPoint" to itemId,
                                    "web" to "${
                                        mobileApplication.dataStoreApp.readDataStoreKey<String>(
                                            BASEURLSALIX
                                        )
                                    }/#!/item/$itemId/summary"
                                )
                            )
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(
                                    title = getString(R.string.titleWebViewer),
                                ), entryPoint = entryPoint
                            )

                        }
                    }

                }

            })

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

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setEvents() {

        binding.editItemFk.requestFocus()
        binding.editItemFk.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (binding.editItemFk.text.toString().isNotEmpty())
                    try {
                        getItemCard(
                            itemScanValue(
                                binding.editItemFk.text.toString(),
                                "buy",
                                "more"
                            ).toString()
                        )
                    } catch (ex: Exception) {
                        ma.messageWithSound(ex.message.toString(), true, true)
                    }

                binding.editItemFk.setText("")
                ma.hideKeyboard(binding.editItemFk)
                return@setOnEditorActionListener true
            }
            false
        }

        binding.mainToolbar.backButton.setOnClickListener {

            requireActivity().onBackPressed()
            customDynamic.removeViewsDialog()
            customDynamic.cancel()

        }

        binding.itemcardImage.setOnClickListener {

            val i = Intent(activity, ImageViewActivity::class.java)
            i.putExtra(getString(R.string.url), urlLarge)
            i.putExtra(getString(R.string.title), titleImage)
            startActivity(i)
        }
    }

    private fun getItemCard(itemFk: String) {

        warehouseFk = mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK) as Int
        binding.splashProgressTwo.visibility = View.VISIBLE
        viewModel.getItemCard(itemFk.toLong(), warehouseFk!!)
        this.itemFk = itemFk

    }

    override fun observeViewModel() {
        with(viewModel) {
            itemcard.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    binding.itemcardLayout.visibility = GONE
                    binding.splashProgressTwo.visibility = GONE
                    binding.mainToolbar.toolbarTitle.text = getString(R.string.itemCard)
                    ma.messageWithSound(it.errorMessage, true, false)

                } else {
                    if (it.id != 0) {
                        binding.itemcardLayout.visibility = View.VISIBLE
                        setItemCard(it)
                        binding.mainToolbar.toolbarIcons.visibility = View.VISIBLE
                    } else {
                        binding.splashProgressTwo.visibility = GONE
                        binding.itemcardLayout.visibility = GONE
                        binding.mainToolbar.toolbarTitle.text = getString(R.string.itemCard)
                        ma.messageWithSound(
                            getString(R.string.itemNotFound),
                            true,
                            false,
                            getString(R.string.noResults)
                        )

                    }

                }
            })

            itemspackinglist.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE

                createItemTypeTypeList(it.list)
            })

            response.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                getItemCard(itemInfoG!!.id.toString())

            })
            addressLosesList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (it.list.isEmpty()) {
                    ma.messageWithSound(getString(R.string.NotAddress), true, false)
                } else {
                    showDialogTrashFault(it.list)
                }

            })

        }
    }

    private fun createItemTypeTypeList(list: List<ItemPackingType>) {
        itemsPackingType.clear()
        list.forEach { item ->
            if (!item.isError) {
                try {
                    itemsPackingType.add(ItemPackingType(item.code, item.description))

                } catch (e: Exception) {
                    getString(R.string.errorInput).toast(requireContext())
                }
            }
        }
    }

    private fun setItemCard(itemInfo: ItemCardVO) {
        itemInfoG = itemInfo
        binding.mainToolbar.toolbarTitle.text = itemInfo.id.toString() + "-" + itemInfo.longName
        titleImage = itemInfo.id.toString() + "-" + itemInfo.longName
        binding.itemcardImage.loadUrl(itemInfo.urlImage200)
        urlLarge = itemInfo.urlImage
        binding.itemcardTag1.text = itemInfo.size.toString()
        binding.itemcardTag2.text = itemInfo.value5
        binding.itemcardTag3.text = itemInfo.value6
        binding.itemcardTag4.text = itemInfo.value7 + " " + itemInfo.origin
        binding.itemcardBuyer.text = itemInfo.buyer
        listItemsRow = ArrayList()

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.total),
                value = itemInfo.visible.toString(),
                isEditable = false
            )
        )

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Disponible),
                value = itemInfo.available.toString(),
                isEditable = false
            )
        )

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Ubicado),
                value = itemInfo.vVisibleItemShelving.toString(),
                isEditable = false
            )
        )

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.SINUBICAR),
                value = itemInfo.unlocated.toString(),
                isEditable = false,
                action = "itemStockUpdate"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.itemCost),
                value = itemInfo.itemCost,
                isEditable = false,
                action = ""
            )
        )

        //EDITABLES

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.titleSimilarItems),
                isEditable = true,
                action = "itemProposal"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.DARALTA),
                value = "",
                isEditable = true,
                action = "itemStockUpdateAdd"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.DARBAJA),
                value = "",
                isEditable = true,
                action = "itemStockUpdateRemove"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.BuscarItem),
                value = "",
                isEditable = true,
                action = "buscarItem"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Grouping),
                value = itemInfo.grouping.toString(),
                isEditable = true,
                action = "updateGrouping"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Packing),
                value = itemInfo.packing.toString(),
                isEditable = true,
                action = "updatePacking"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.stems),
                value = itemInfo.stems,
                isEditable = true,
                action = "itemSaveStem"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Referencia),
                value = itemInfo.reference,
                isEditable = true,
                action = "item_saveReference"
            )
        )
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Barcode),
                barcodes = itemInfo.barcodes,
                isEditable = true,
                action = "toBarcode"
            )
        )
        listBarcodes = itemInfo.barcodes as ArrayList<BarcodeVO>

        adapter = ItemCardAdapter(listItemsRow, object : OnItemCardRowClickListener {
            override fun onItemCardRowClickListener(item: ItemCardRowVO) {

                when (item.action) {
                    "itemProposal" -> {
                        ma.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = getString(R.string.titleSearchSimilarItems)
                            ), itemInfoG!!.id.toString()
                        )
                    }

                    "toBarcode" -> {
                        prepareBarcodeDialog()
                    }

                    "buscarItem" -> {
                        ma.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = getString(R.string.titleItemSearch)
                            ), itemInfoG!!.id.toString()
                        )
                    }

                    "itemStockUpdateRemove", "itemStockUpdateAdd" -> {
                        customDialogInput.getEditText().setRawInputType(
                            InputType.TYPE_CLASS_NUMBER
                        )
                        showCustomDialog(
                            item, if (item.action == "itemStockUpdateRemove") {
                                getString(R.string.quantityToUnregister)
                            } else {
                                getString(R.string.quantityToRegister)
                            }
                        )

                    }

                    else -> {
                        showCustomDialog(
                            item, getString(R.string.currentVAlue)
                        )
                    }
                }

            }
        })
        binding.itemcardRecyclerview.adapter = adapter
        binding.itemcardRecyclerview.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.scrollView.post {
            val position = IntArray(2)
            binding.itemcardImage.getLocationInWindow(position)
            binding.scrollView.scrollTo(0, position[1])
        }
        binding.splashProgressTwo.visibility = GONE
    }

    private fun showCustomDialog(item: ItemCardRowVO, textDescrip: String) {

        customDialogInput.setTitle(item.title!!)
            .setDescription(textDescrip)
            .setOkButton(getString(R.string.save)) {
                customDialogAdd(item)
                customDialogInput.dismiss()

            }.setKoButton(getString(R.string.cancel)) {
                ma.hideKeyboard(customDialogInput.getEditText())
                customDialogInput.dismiss()
            }.setValue("").show()
        customDialogInput.getEditText().requestFocus()
        customDialogInput.getEditText()
            .setOnEditorActionListener { _, actionId, _ ->
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                    customDialogAdd(item)
                    return@setOnEditorActionListener true
                }
                false
            }
    }

    private fun customDialogAdd(item: ItemCardRowVO) {
        try {
            editItemCardRow(
                item,
                customDialogInput.getValue().toInt()
            )
            customDialogInput.setValue("")
            customDialogInput.dismiss()
            ma.hideKeyboard(customDialogInput.getEditText())
        } catch (ex: Exception) {

            if (item.action == "itemSaveStem"
            ) {
                viewModel.item_saveStems(
                    itemFk = itemInfoG!!.id,
                    value = null
                )
            } else {
                getString(R.string.errorInput).toast(requireContext())
            }
        }
    }

    private fun editItemCardRow(item: ItemCardRowVO, value: Int) {
        when (item.action) {
            "itemStockUpdateAdd" -> {
                showProgress()
                viewModel.setVisibleDiscard(itemInfoG!!.id, warehouseFk!!, value * -1, null)
            }

            "itemStockUpdateRemove" -> prepareItemStockUpdate2(item, value)
            "updateGrouping" ->
                viewModel.updateGrouping(
                    warehouseFk = warehouseFk!!,
                    itemFk = itemInfoG!!.id,
                    value = value,

                    )

            "updatePacking" -> viewModel.updatePacking(
                warehouseFk = warehouseFk!!,
                itemFk = itemInfoG!!.id,
                value = value,

                )

            "itemSaveStem" -> viewModel.item_saveStems(
                itemFk = itemInfoG!!.id,
                value = value
            )

            "item_saveReference" -> viewModel.item_saveReference(
                itemFk = itemInfoG!!.id,
                value = value
            )

        }
        if (item.action != "itemStockUpdate" && item.action != "itemStockUpdateRemove" && item.action != "itemStockUpdateAdd")
            showProgress()
    }

    private fun prepareItemStockAdd(value: Int) {

        showProgress()
        viewModel.itemTrash(
            itemFk = itemInfoG!!.id,
            warehouseFk = warehouseFk!!,
            newValue = (value * -1),
            isTrash = false

        )
    }

    private fun showProgress() {
        binding.splashProgress.visibility = View.VISIBLE
    }

    private fun prepareItemStockUpdate2(itemB: ItemCardRowVO, value: Int) {

        //Tarea 5652 , quitar código cuando está asignada tarea
        /*    val test = true
            if (test) {*/

        viewModel.getAddress()
        quantityToDiscard = value

        /* } else {
             try {

                 if (itemB.action == "itemStockUpdateRemove") {

                     customDialogTwo.setTitle(itemB.title!!)
                         .setDescription(getString(R.string.deleteStock))
                         .setOkButton(getString(R.string.fault)) {
                             viewModel.itemTrash(
                                 itemFk = itemInfoG!!.id,
                                 warehouseFk = warehouseFk!!,
                                 newValue = value,
                                 isTrash = false

                             )
                             showProgress()
                             customDialogTwo.dismiss()

                         }.setOkButtonTwo(getString(R.string.trash)) {
                             viewModel.itemTrash(
                                 itemFk = itemInfoG!!.id,
                                 warehouseFk = warehouseFk!!,
                                 newValue = value,
                                 isTrash = true
                             )

                             showProgress()
                             customDialogTwo.dismiss()

                         }.setKoButton(getString(R.string.cancel)) {

                             customDialogTwo.dismiss()
                         }.show()

                 } else {

                     showProgress()
                     viewModel.itemTrash(
                         itemFk = itemInfoG!!.id,
                         warehouseFk = warehouseFk!!,
                         newValue = (value * -1),
                         isTrash = false

                     )
                 }
             } catch (e: Exception) {
                 //  binding.itemcardLayout.visibility = View.GONE
                 ma.messageWithSound(getString(R.string.errorNotNumber), true, true)

             }
         }*/
    }

    private fun showDialogTrashFault(listAddress: List<AddressLoses>) {

        customDynamic.setTitle("")
        customDynamic.setDescription(getString(R.string.deleteStock))
        customDynamic.createDynamicButtons(listAddress)
        customDynamic.show()

    }

    private fun prepareBarcodeDialog() {

        customDialogList.setTitle(getString(R.string.barcodes))
            .setOkButton(getString(R.string.save)) {
                setUpdateBarcode()
            }.setKoButton(getString(R.string.close)) {
                ma.hideKeyboard(customDialogList.getEditText())
            }.setValue("").show()

        customDialogList.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                setUpdateBarcode()
                return@setOnEditorActionListener true
            }
            false
        }

        barcodeAdapter = BarcodeAdapter(listBarcodes, object : OnBarcodeRowClickListener {
            override fun onBarcodeRowClickListener(item: BarcodeVO) {
                updateBarcode(item.code!!, true)
                customDialogList.setValue("")
                customDialogList.dismiss()
            }
        })
        customDialogList.getRecyclerView().adapter = barcodeAdapter

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

    private fun setUpdateBarcode() {
        try {
            ma.hideKeyboard(customDialogList.getEditText())
            if (customDialogList.getValue().isNotEmpty())
                updateBarcode(customDialogList.getValue(), false)
            customDialogList.setValue("")
            customDialogList.dismiss()

        } catch (ex: Exception) {
            getString(R.string.errorInput).toast(requireContext())
        }

    }

    private fun updateBarcode(code: String, delete: Boolean) {
        if (delete) {
            var i = 0
            var posDelete = 0
            listBarcodes.forEach {
                if (it.code == code)
                    posDelete = i
                i += 1
            }
            listBarcodes.removeAt(posDelete)

            viewModel.barcodesEdit(
                itemFk = itemInfoG!!.id,
                value = code,
                delete = delete,
            )
        } else {
            listBarcodes.add(BarcodeVO(code))
            viewModel.barcodesEditSalix(
                itemFk = itemInfoG!!.id,
                barCodeValue = code
            )

        }

        barcodeAdapter!!.notifyDataSetChanged()
        showProgress()
    }

    private fun showDialogSelectItemTypePacking() {

        var array = arrayOfNulls<String>(itemsPackingType.size)
        for (indice in array.indices) {
            array[indice] =
                itemsPackingType[indice].code + " : " + itemsPackingType[indice].description
        }
        val builder = AlertDialog.Builder(this.context)
        builder.setTitle(getString(R.string.mensajeseleccionencajado))
            .setItems(
                array
            ) { _, position ->

                updateItemPackingType(itemsPackingType[position].code)

            }

        builder.create().show()
    }

    private fun updateItemPackingType(itemPackingType: String) {
        binding.splashProgress.visibility = View.VISIBLE
        viewModel.updatePackingTypeSalix(
            itemInfoG!!.id,
            itemPackingType
        )
    }

    override fun onClickDynamic(addressFK: Int) {

        binding.splashProgress.visibility = View.VISIBLE
        viewModel.setVisibleDiscard(itemInfoG!!.id, warehouseFk!!, quantityToDiscard, addressFK)
        customDynamic.dismiss()
        customDynamic.cancel()
    }

}


