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

import android.content.Context
import android.graphics.drawable.Drawable
import android.text.InputType
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentSacadorBinding
import es.verdnatura.domain.ConstAndValues.PRINTERNAME
import es.verdnatura.domain.ConstAndValues.SECTORFK
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnCollectionTicketSelectedListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.TAG
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.convertToDateString
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.feature.sacador.adapter.CollectionAdapterNew
import es.verdnatura.presentation.view.feature.sacador.model.CollectionTicket
import java.text.SimpleDateFormat
import java.util.Calendar

class SacadorFragmentNew(
    var type: String
) :
    BaseFragment<FragmentSacadorBinding, SacadorViewModel>(SacadorViewModel::class) {

    private var onCollectionSelectedListener: OnCollectionTicketSelectedListener? = null
    private var goBack: Boolean = false
    private var goBack2: Boolean = false
    private lateinit var customDialog: CustomDialog
    private lateinit var customDialogInput: CustomDialogInput
    private var collectionsList: ArrayList<CollectionTicket> = ArrayList()
    private var adapter: CollectionAdapterNew? = null

    companion object {
        fun newInstance(type: String) = SacadorFragmentNew(type)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnCollectionTicketSelectedListener) onCollectionSelectedListener = context
    }

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

    override fun init() {
        customDialog = CustomDialog(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        binding.mainToolbar.toolbarTitle.text = getString(R.string.getcollection)
        setToolBar()
        setEvents()
        callBack(type)
        super.init()
    }

    private fun callBack(type: String) {

        when (type) {
            "PREPARED" -> {
                viewModel.collectionGetSalixLocal()
            }

            "PREITEMPICKER" -> {
                viewModel.sectorCollectionGet()
            }

            "PREITEMPICKERTEST" -> {
                viewModel.sectorCollectionPartial()
            }

            else -> {

            }
        }
    }

    override fun onPause() {
        goBack = true
        goBack2 = true
        super.onPause()
    }

    private fun setToolBar() {

        ma.hideBottomNavigation(View.VISIBLE)
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconAdd = ImageView(context)
        iconAdd.setImageResource(R.drawable.ic_add_black_24dp)
        val iconVehicleIn = ImageView(context)
        iconVehicleIn.setImageResource(R.drawable.car)
        val iconPrint = ImageView(context)
        iconPrint.setImageResource(R.drawable.ic_print_black_24dp)

        iconAdd.tooltipText = getTooltip(R.drawable.ic_add_black_24dp)
        iconVehicleIn.tooltipText = getTooltip(R.drawable.car)
        iconAdd.tooltipText = getTooltip(R.drawable.ic_add_black_24dp)
        iconPrint.tooltipText = getTooltip(R.drawable.ic_print_black_24dp)

        if (type == "PREPARED") {
            listIcons.add(iconVehicleIn)
        } else {
            listIcons.add(iconPrint)
        }
        listIcons.add(iconAdd)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {

                        iconAdd.drawable -> {

                            if (type == "PREPARED") {
                                if (hasSector())
                                viewModel.collection_assignNew(
                                )
                            } else {
                                if (hasSector())
                                viewModel.sectorCollectionNew(
                                    mobileApplication.dataStoreApp.readDataStoreKey(
                                        SECTORFK
                                    )
                                )
                            }

                        }

                        iconVehicleIn.drawable -> ma.onVehicleSelected(SacadorFragment.TAG)
                        iconPrint.drawable -> {
                            showPrintPrevious()
                        }
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun showPrintPrevious() {

        customDialogInput.setInputText(InputType.TYPE_CLASS_NUMBER)
        customDialogInput.setTitle(getString(R.string.printTicket))
        customDialogInput.setDescription(getString(R.string.printPreviousGroup))
            .setValue("")
            .setOkButton(getString(R.string.print)) {

                print()

            }.setKoButton(getString(R.string.cancel)) {
                customDialogInput.dismiss()
            }.show()
        customDialogInput.setFocusText()
        ma.hideKeyboard(customDialogInput.getEditText())

        customDialogInput.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                print()

                return@setOnEditorActionListener true
            }
            false
        }

    }

    private fun print() {

        try {
            if (customDialogInput.getValue().isNotEmpty()
            ) {
                if (ma.havePrinter()) {
                    viewModel.ticketPrintLabelPrevious(customDialogInput.getValue().toInt())
                    (getString(R.string.Imprimiendo) + mobileApplication.dataStoreApp.readDataStoreKey<String>(
                        PRINTERNAME
                    )).toast(
                        requireContext()
                    )
                } else {
                    getString(R.string.selectPrinter).toast(requireContext())
                }
            }

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

    }

    private fun setEvents() {
        binding.sacadorSwipe.setOnRefreshListener {
            callBack(type)
            binding.sacadorSwipe.isRefreshing = false
        }
    }

    override fun observeViewModel() {

        with(viewModel) {

            collectionListLocal.observe(viewLifecycleOwner) {
                //if (!goBack2)

                createCollectionList(it.list)

                goBack2 = false
            }

            collectionList.observe(viewLifecycleOwner) { it ->
                //if (!goBack2)
                val myCollectionsList = mutableListOf<CollectionTicket>()
                it.list.forEach {
                    //lolass

                    var myDate = getCalendarForDateMinusOneDay(requireContext()).convertToDateString()
                    if (!it.created.contains(myDate)) {
                        myCollectionsList.add(CollectionTicket(it.collectionFk, it.created))
                    }
                }
                createCollectionList(myCollectionsList)
                goBack2 = false
            }

            response.observe(viewLifecycleOwner) {

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

                } else {
                    if (it.response.isNotBlank()) {
                        addCollectionToList(it.response.toInt())

                    } else {
                        when (type) {
                            "PREPARED" -> {
                                viewModel.collectionGetSalixLocal()
                            }

                            "PREITEMPICKER" -> {
                                viewModel.sectorCollectionGet()
                            }

                            "PREITEMPICKERTEST" -> {
                                println("SacadorFragmentNew sectorCollectionGET")
                                // viewModel.sectorCollectionGet()
                                viewModel.sectorCollectionPartial()
                            }

                            else -> {

                            }
                        }
                    }
                }
                goBack = false
                //callBack(type)
            }

        }
    }

    fun getCalendarForDateMinusOneDay(context: Context): Calendar {
        val cal = Calendar.getInstance()
        cal.add(Calendar.DAY_OF_YEAR, -1)
        val sdf = SimpleDateFormat(context.getString(R.string.dateFormat))
        val formattedDate = sdf.format(cal.time)
        val resultCal = Calendar.getInstance()
        resultCal.time = sdf.parse(formattedDate)!!
        return resultCal
    }

    private fun createCollectionList(collections: List<CollectionTicket>) {
        collectionsList = ArrayList()

        collections.forEach {
            collectionsList.add(it)
        }
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = CollectionAdapterNew(collectionsList, onCollectionSelectedListener!!, type)
        binding.fragmentSacadorCollections.layoutManager = lm
        binding.fragmentSacadorCollections.adapter = adapter
        adapter!!.notifyDataSetChanged()

    }

    private fun addCollectionToList(collection: Int) {
        var isNew = true

        collectionsList.forEach {
            if (it.collectionFk == collection) {
                isNew = false
            }
        }
        if (isNew) {
            collectionsList.add(
                CollectionTicket(
                    collectionFk = collection,
                    created = getString(R.string.newCreated)
                )
            )
        } else {
            customDialog.setTitle(getString(R.string.info))
                .setDescription(getString(R.string.collectionPending) + collection)
                .setOkButton(getString(R.string.accept)) {
                    customDialog.dismiss()
                }.show()
        }
        adapter?.notifyDataSetChanged()
    }
    private fun hasSector(): Boolean {
        return if (ma.haveSector()) {
            true
        } else {
            ma.messageWithSound(
                message = getString(R.string.errorSector),
                isError = true,
                isPlayed = true,
                isToasted = false
            )
            false
        }

    }
}
