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

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.QaualityFragmentBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.calidad.adapter.ItemBuyersAdapter
import es.verdnatura.presentation.view.feature.calidad.model.ItemBuyerVO
import java.text.SimpleDateFormat
import java.util.*

class QaualityFragment(
    var userFk : String = "0"
) : BaseFragment<QaualityFragmentBinding,QaualityViewModel>(QaualityViewModel::class) {

    private lateinit var customDialog: CustomDialog
    private var buyersAdapter: ItemBuyersAdapter? = null
    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var onStarSelectedListener : OnStarSelectedListener? = null
    private var listItems:List<ItemBuyerVO> = listOf()
    private var lm : LinearLayoutManager? = null
    private var storedPosition: Int = 0
    private var goBack:Boolean = false


    companion object {
        fun newInstance(userFk:String) = QaualityFragment(userFk)
    }

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

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

    override fun onCreate(savedInstanceState: Bundle?) {
        viewModel.itemShelvingBuyerTask(user = getData(USER),password = getData(PASSWORD),userFk = userFk)
        super.onCreate(savedInstanceState)
    }

    override fun init() {
        customDialog = CustomDialog(requireContext())
        ma.hideBottomNavigation(View.GONE)
        binding.splashProgress.visibility = View.VISIBLE
        binding.mainToolbar.toolbarTitle.text = getString(R.string.qualityFragment)
        setToolBar()
        setEvents()
        super.init()
    }

    override fun onPause() {
        super.onPause()
        goBack = true
        storedPosition = lm?.findFirstVisibleItemPosition() ?: 0
    }

    private fun setToolBar(){
        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconReload = ImageView(context)
        iconReload.setImageResource(R.drawable.ic_autorenew_black_24dp)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            iconReload.tooltipText = getTooltip(R.drawable.ic_autorenew_black_24dp)

        }
        listIcons.add(iconReload)
        binding.mainToolbar.toolbarIcons.adapter = ToolBarAdapterTooltip(listIcons,object: OnOptionsSelectedListener {
            override fun onOptionsItemSelected(item: Drawable) {
                if (item == iconReload){
                    binding.splashProgress.visibility = View.VISIBLE
                    viewModel.itemShelvingBuyerTask(user = getData(USER),password = getData(PASSWORD),userFk = userFk)
                }
            }
        })
        binding.mainToolbar.toolbarIcons.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun setEvents(){
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        //ESCANER =========
        hideKeyboards()
        binding.scanInput.requestFocus()
         binding.scanInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (! binding.scanInput.text.toString().isEmpty()){
                    findSale( binding.scanInput.text.toString())
                }
                 binding.scanInput.setText("")
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            true
        }
    }

    private fun hideKeyboards(){
        try{
            requireActivity().hideKeyboard()
        }catch (e:Exception){}
    }

    override fun observeViewModel() {
        with(viewModel) {
            buyersList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                createBuyerList(it.list)
            })

            response.observe(viewLifecycleOwner, Observer {
                viewModel.itemShelvingBuyerTask(user = getData(USER),password = getData(PASSWORD),userFk = userFk)
            })
        }
    }

    private fun createBuyerList(list:List<ItemBuyerVO>){
        list.forEach { item ->
            if (!goBack){
                if (item.created != ""){
                    item.created = getCalendarFromDate(item.created).convertToDateString()
                }
            }

            if (item.visible.contains(getString(R.string.visible),ignoreCase = true)){
                item.visible = item.visible
            }else{
                item.visible = getString(R.string.visible)+item.visible
            }

            item.iconResourceOk = R.drawable.ic_start_ok
            item.iconResourceKo = R.drawable.ic_star_ko
        }
        goBack = false
        listItems = list
        buyersAdapter = ItemBuyersAdapter(listItems,pasillerosItemClickListener!!,object: OnStarSelectedListener{
            override fun onStarSelected(vId: String, vStars: String) {
                binding.splashProgress.visibility = View.VISIBLE
                viewModel.itemShelvingStarsUpdate(getData(USER),getData(PASSWORD),vId,vStars)
            }

        })
        binding.shelvingBuyersItems.adapter = buyersAdapter
        lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        binding.shelvingBuyersItems.layoutManager = lm

        if (storedPosition < listItems.size)
            goToPosition(storedPosition)
    }

    private fun getCalendarFromDate(date:String): Calendar {
        val sdf = SimpleDateFormat(getString(R.string.dateFormat))
        val cal = Calendar.getInstance()
        cal.time = sdf.parse(date)!!
        return cal
    }

    private fun findSale(matricula:String){
        var isSearch = false
        var index = 0
        var position = 0
        listItems.forEach { item ->
            if (item.shelvingFk.uppercase() == matricula.uppercase()){
                item.showStars = true
                if (!isSearch){
                    position = index
                    isSearch = true
                }
            }else{
                item.showStars = false
            }
            index += 1
        }

        storedPosition = position
        goToPosition(position)

        buyersAdapter?.notifyDataSetChanged()
    }

    private fun goToPosition(position:Int){
        binding.shelvingBuyersItems.addViewObserver {
            lm!!.scrollToPositionWithOffset(position,0)
        }
    }

}