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

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Log
import android.util.TypedValue
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentVehiclecontrolBinding
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogThreeButtons
import es.verdnatura.presentation.view.feature.historicovehiculo.fragment.HistoricoVehiculoFragment
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.sacador.fragment.SacadorFragment

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ControlVehiculoFragment(
    var tagName: String = ""
) : BaseFragment<FragmentVehiclecontrolBinding, ControlVehiculoViewModel>(
    ControlVehiculoViewModel::class
) {

    private var goBack: Boolean = false
    private var onCollectionSelectedListener: OnCollectionSelectedListener? = null
    override fun getLayoutId(): Int = R.layout.fragment_vehiclecontrol
    private lateinit var customDialog: CustomDialog
    private var isWorkedTimed = "UNREGISTERED"
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogThreeButtons: CustomDialogThreeButtons

    companion object {
        fun newInstance(tagName: String) = ControlVehiculoFragment(tagName)
    }

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

    override fun init() {

        customDialog = CustomDialog(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        customDialogThreeButtons = CustomDialogThreeButtons(requireContext())
        goBack = false

        binding.splashProgress.visibility = GONE


        if (tagName.equals(HistoricoVehiculoFragment.TAG)) {
            setToolBar("HISTORY")
            showScanner(getString(R.string.scanShelvingHistorical), "HISTORY")
        } else {

            checkControlTimeVehicle()
            setToolBar("ALL")
        }


        setEvents()
        super.init()
    }


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

    private fun setToolBar(direction: String?) {

        binding.mainToolbar.toolbarTitle.text = getString(R.string.vehiclecontrol)
        binding.mainToolbar.toolbarTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13F)

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconHistory = ImageView(context)
        iconHistory.setImageResource(R.drawable.ic_history_black_24dp)
        val iconVehicleIn = ImageView(context)
        iconVehicleIn.setImageResource(R.drawable.car)
        val iconVehicleOut = ImageView(context)
        iconVehicleOut.setImageResource(R.drawable.car_off)


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            iconHistory.tooltipText = getTooltip(R.drawable.ic_history_black_24dp)
            iconVehicleIn.tooltipText = getTooltip(R.drawable.car)
            iconVehicleOut.tooltipText = getTooltip(R.drawable.car_off)

        }

        when (direction) {
            "OUT" -> {
                listIcons.remove(iconVehicleIn)
                listIcons.add(iconVehicleOut)
                listIcons.add(iconHistory)
            }
            "IN" -> {
                listIcons.remove(iconVehicleOut)
                listIcons.add(iconVehicleIn)
                listIcons.add(iconHistory)
            }
        }


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

                    when (item) {
                        iconHistory.drawable -> showScanner(
                            getString(R.string.scanShelvingHistorical),
                            "HISTORY"
                        )
                        iconVehicleIn.drawable -> showScanner(getString(R.string.scanPlate), "IN")
                        iconVehicleOut.drawable -> showScanner(
                            getString(R.string.scanPlateTakeoff),
                            "OUT"
                        )
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun showScanner(description: String, action: String) {

        customDialogInput.setTitle(getString(R.string.vehiclecontrol)).setDescription(description)
            .setOkButton(getString(R.string.accept)) {
                if (customDialogInput.getValue().isNotEmpty()) {
                    // "$description ${customDialogInput.getValue()} OK".toast(requireContext())
                    insertControlTimeVehicle(customDialogInput.getValue(), action)
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
            }

            .setKoButton(getString(R.string.cancel)) {
                customDialogInput.dismiss()
                if (tagName.equals(HistoricoVehiculoFragment.TAG)) {
                    ma.onBackPressed()
                }

            }.setValue("").show()

        customDialogInput.setFocusText()

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

                if (customDialogInput.getValue().isNotEmpty()) {

                    insertControlTimeVehicle(customDialogInput.getValue(), action)
                }
                customDialogInput.setValue("")
                scanRequest()
                customDialogInput.dismiss()
                hideKeyboards()
                return@setOnEditorActionListener true
            }
            false
        }

    }

    private fun checkControlTimeVehicle() {

        if (!goBack) {

            binding.splashProgress.visibility = VISIBLE
            viewModel.workerMachinery_isRegistered(getData(USER), getData(PASSWORD))

        }
    }

    private fun insertControlTimeVehicle(plateNumber: String, direction: String) {

        if (direction.equals("HISTORY")) {


            ma.onPasillerosItemClickListener(
                PasillerosItemVO(title = getString(R.string.titleHistoricalHide)),
                plateNumber
            )
        } else if (direction.equals("IN")) {
            binding.splashProgress.visibility = VISIBLE
            viewModel.machineWorker_add(getData(USER), getData(PASSWORD), plateNumber)

        } else if (direction.equals("OUT")) {
            viewModel.machineWorker_update(getData(USER), getData(PASSWORD), plateNumber)

        } else if (direction.equals("")) {
            ma.openFragmentPickers(true)
        }

    }

    private fun scanRequest() {
        //  if (binding.scanInput != null) {
        binding.scanInput.requestFocus()
        //}
        hideKeyboards()
    }

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


    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            ma.openFragmentPickers(true)
            //requireActivity().onBackPressed()

        }

        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!binding.scanInput.text.isNullOrEmpty()) {

                    if (tagName.equals(HistoricoVehiculoFragment.TAG)) {
                        showOptionsHistorical(binding.scanInput.text.toString())
                    } else {
                        showOptionsVehicleControl(binding.scanInput.text.toString())
                    }
                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }
    }

    private fun showOptionsVehicleControl(plate: String) {

        customDialogThreeButtons.setCustomDialogValue(GONE)

        customDialogThreeButtons.setDescription(getString(R.string.doVehiclePlate) + plate + "?")
            .setValue(plate)
        if (isWorkedTimed.equals("UNREGISTERED")) {
            customDialogThreeButtons.setOkButtonTwo("COGER") {
                if (customDialogThreeButtons.getValue().trim().isEmpty()) {
                    getString(R.string.returnScan).toast(requireContext())
                } else {
                    binding.splashProgress.visibility = VISIBLE
                    customDialogThreeButtons.dismiss()
                    insertControlTimeVehicle(customDialogThreeButtons.getValue(), "IN")
                }
            }
        } else {

            customDialogThreeButtons.setOkButtonThree("DEJAR") {
                if (customDialogThreeButtons.getValue().trim().isEmpty()) {
                    getString(R.string.returnScan).toast(requireContext())
                } else {
                    binding.splashProgress.visibility = VISIBLE
                    customDialogThreeButtons.dismiss()
                    insertControlTimeVehicle(customDialogThreeButtons.getValue(), "OUT")
                }
            }
        }.setOkButtonFour(getString(R.string.historical)) {
            if (customDialogThreeButtons.getValue().trim().isEmpty()) {
                getString(R.string.returnScan).toast(requireContext())
            } else {
                customDialogThreeButtons.dismiss()
                insertControlTimeVehicle(customDialogThreeButtons.getValue(), "HISTORY")

            }

        }.setKoButton(getString(R.string.cancel)) {
            scanRequest()
            customDialogThreeButtons.dismiss()
        }.show()
    }

    private fun showOptionsHistorical(plate: String) {

        customDialogThreeButtons.setCustomDialogValue(GONE)

        customDialogThreeButtons.setDescription(getString(R.string.doVehiclePlate) + plate + "?")

            .setValue(plate)

            .setOkButtonFour(getString(R.string.historical)) {
                if (customDialogThreeButtons.getValue().trim().isEmpty()) {
                    getString(R.string.returnScan).toast(requireContext())
                } else {
                    customDialogThreeButtons.dismiss()
                    insertControlTimeVehicle(customDialogThreeButtons.getValue(), "HISTORY")

                }

            }.setKoButton(getString(R.string.cancel)) {
                scanRequest()
                customDialogThreeButtons.dismiss()
            }.show()
    }

    override fun observeViewModel() {

        with(viewModel) {
            binding.splashProgress.visibility = GONE
            responseinsert.observe(viewLifecycleOwner, {

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

                } else {
                    if (it.response == "false") {

                        customDialog.setTitle(getString(R.string.error))
                            .setDescription(getString(R.string.reviewCAllhistorical))
                            .setOkButton(getString(R.string.close)) {
                                customDialog.dismiss()
                            }.show()

                    } else {
                        if (it.response == "true") {
                            ma.openFragmentPickers(false)
                            //ma.onPasillerosItemClickListener( PasillerosItemVO(title = "Sacadores"),"CONTROL")
                            //checkControlTimeVehicle()
                        }

                    }
                }
                binding.splashProgress.visibility = GONE
            })

            responsecontrol.observe(viewLifecycleOwner, {
                binding.splashProgress.visibility = GONE

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

                } else {
                    if (it.response.equals("1")) {
                        isWorkedTimed = "REGISTERED"
                        setToolBar("OUT")

                        if (!tagName.equals(SacadorFragment.TAG)) {
                            ma.openFragmentPickers(false)
                        }

                    } else {

                        if (it.response.equals("0")) {
                            setToolBar("IN")

                            customDialogInput.setTitle(getString(R.string.vehiclecontrol))
                                .setDescription(getString(R.string.scanPlate))
                                .setOkButton(getString(R.string.takeVehicle)) {
                                    if (customDialogInput.getValue().isNotEmpty()) {
                                        // "$description ${customDialogInput.getValue()} OK".toast(requireContext())
                                        insertControlTimeVehicle(customDialogInput.getValue(), "IN")
                                    }
                                    customDialogInput.setValue("")
                                    scanRequest()
                                    customDialogInput.dismiss()
                                    hideKeyboards()
                                }

                                .setKoButton(getString(R.string.noVehicle)) {
                                    customDialogInput.dismiss()
                                    ma.openFragmentPickers(true)
                                    /* if (tagName.equals(HistoricoVehiculoFragment.TAG)) {
                                         ma.onBackPressed()
                                     }*/

                                }.setValue("").show()

                            customDialogInput.setFocusText()

                        }
                    }
                }
            })

        }

    }


}


