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

import android.content.Intent
import android.graphics.drawable.Drawable
import android.text.InputType
import android.view.View
import android.view.View.GONE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import es.verdnatura.R
import es.verdnatura.databinding.FragmentItemCardBinding
import es.verdnatura.domain.ConstAndValues.WAREHOUSEFK
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnClickDynamic
import es.verdnatura.presentation.common.OnItemCardRowClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.common.loadUrl
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.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
    private var positionToReturnY = 0

    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

    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)


        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 = R.string.titleHistorical),
                                itemInfoG!!.id.toString()
                            )

                        }

                        iconSalix.drawable -> {

                            val itemId = itemInfoG!!.id
                            val entryPoint = Gson().toJson(
                                mutableMapOf(
                                    "entryPoint" to itemId, "web" to "${
                                        mobileApplication.dataStoreApp.getServerSalix()
                                    }/#!/item/$itemId/summary"
                                )
                            )
                            ma.onPasillerosItemClickListener(
                                PasillerosItemVO(
                                    title = R.string.titleWebViewer,
                                ), entryPoint = entryPoint
                            )

                        }
                    }

                }

            })

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

    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(), arrayOf("buy"), "more"
                        ).toString()
                    )
                } catch (ex: Exception) {
                    ma.messageWithSound(ex.message.toString(), isError = true, isPlayed = true)
                }

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

        binding.mainToolbar.backButton.setOnClickListener {

            ma.onMyBackPressed()
            customDynamic.removeViewsDialog()
            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(itemValueFk: String) {

        warehouseFk = mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK) as Int
        itemFk = itemValueFk

        viewModel.getItemCard(itemFk.toLong(), warehouseFk!!)

    }

    override fun observeViewModel() {
        with(viewModel) {
            loadResponseItemCard.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

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

                    }
                }
            }

            loadAddressLosesList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {

                    if (it.list.isEmpty()) {
                        ma.messageWithSound(
                            getString(R.string.NotAddress), isError = true, isPlayed = false
                        )
                    } else {
                        showDialogTrashFault(it.list)
                    }

                }
            }
        }
    }

    private fun setItemCard(itemInfo: ItemCardVO) {
        itemInfoG = itemInfo
        binding.mainToolbar.toolbarTitle.text =
            getString(R.string.itemCardTitle, 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 =
            getString(R.string.itemCardTag, itemInfo.value7, itemInfo.origin)
        binding.itemcardBuyer.text = itemInfo.buyer
        listItemsRow = ArrayList()

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

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

        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.Ubicado),
                value = (itemInfo.vVisibleItemShelving ?: "0").toString(),
                isEditable = false
            )
        )
        val unlocated = ((itemInfo.visible ?: 0) - (itemInfo.vVisibleItemShelving ?: 0)).toString()
        listItemsRow.add(
            ItemCardRowVO(
                title = getString(R.string.SINUBICAR),
                value = unlocated,
                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) {

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

                    "toBarcode" -> {
                        prepareBarcodeDialog()
                    }

                    "buscarItem" -> {
                        ma.onPasillerosItemClickListener(
                            PasillerosItemVO(
                                title = 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)

        if (positionToReturnY == 0) binding.scrollView.post {
            val position = IntArray(2)
            binding.itemcardImage.getLocationInWindow(position)
            binding.scrollView.scrollTo(0, position[1])
        } else {
            binding.scrollView.post {
                binding.scrollView.smoothScrollTo(0, positionToReturnY)
            }
        }

    }

    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("")
            ma.hideKeyboard(customDialogInput.getEditText())
            customDialogInput.dismiss()
        } catch (ex: Exception) {

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

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

            "itemStockUpdateRemove" -> {
                viewModel.getAddress()
                quantityToDiscard = value
            }

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

            }

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

                )

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

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

        }

    }

    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("")
            ma.hideKeyboard(customDialogList.getEditText())
            customDialogList.dismiss()

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

    }

    private fun updateBarcode(code: String, delete: Boolean) {

        viewModel.barcodesEditSalix(
            itemFk = itemInfoG!!.id,
            barCodeValue = code,
            delete = delete,
            warehouseFk = warehouseFk!!
        )
    }

    override fun onClickDynamic(addressFK: Int) {

        viewModel.setVisibleDiscard(itemInfoG!!.id, warehouseFk!!, quantityToDiscard, addressFK)
        customDynamic.dismiss()
        customDynamic.cancel()
    }

}