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

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.widget.PopupMenu
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentStopmapTruckListBinding
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.GeneralAdapter
import es.verdnatura.presentation.common.GeneralItem
import es.verdnatura.presentation.common.OnGeneralItemRowClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnStopMapClickListener
import es.verdnatura.presentation.common.TAG
import es.verdnatura.presentation.common.addFragment
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.pasillero.fragment.PasilleroFragment
import es.verdnatura.presentation.view.feature.roadmap.adapter.StopMapListAdapter
import es.verdnatura.presentation.view.feature.roadmap.model.RoadMapTruck
import es.verdnatura.presentation.view.feature.roadmap.model.RoadStopMapTruck
import es.verdnatura.presentation.view.feature.roadmap.model.RoadStopMapTruckList
import es.verdnatura.presentation.view.feature.roadmap.model.TruckAction

class StopMapListFragment(
    private var title: String,
    private var roadMap: RoadMapTruck
) : BaseFragment<FragmentStopmapTruckListBinding, RoadMapListViewModel>(
    RoadMapListViewModel::class
) {

    private var adapter: StopMapListAdapter? = null
    private var onStopMapClickListener: OnStopMapClickListener? = null
    private var originalList = listOf<RoadStopMapTruck>()

    companion object {
        fun newInstance(title: String, roadMap: RoadMapTruck) = StopMapListFragment(title, roadMap)
        private const val REQUEST_CALL_PERMISSION = 1
    }

    override fun onAttach(context: Context) {
        if (context is OnStopMapClickListener) onStopMapClickListener = context
        super.onAttach(context)
    }

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

    override fun init() {

        binding.mainToolbar.toolbarTitle.text =
            getString(R.string.doublePointText, title, roadMap.trailerPlate)

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        setToolBar()
        viewModel.getStopMapTruckList(roadMap.id)
        super.init()
    }

    private fun setFilter() {
        binding.filterTxt.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?, start: Int, count: Int, after: Int
            ) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {

                adapter!!.setList(originalList.filter { stopMapTruck ->
                    stopMapTruck.toString().contains(
                        s.toString(), ignoreCase = true
                    )
                })

            }
        })
        binding.filterTxt.requestFocus()

    }

    private fun setToolBar() {
        val listIcons: ArrayList<Drawable> = ArrayList()
        val iconReload: Drawable = ResourcesCompat.getDrawable(
            resources, R.drawable.ic_autorenew_black_24dp, null
        )!!

        val iconSettings: Drawable = ResourcesCompat.getDrawable(
            resources, R.drawable.ic_setting_ui, null
        )!!

        listIcons.add(iconReload)
        listIcons.add(iconSettings)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapter(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    when (item) {
                        iconReload -> viewModel.getStopMapTruckList(roadMap.id)
                        iconSettings -> {
                            ma.addFragment(
                                RoadMapSettingsFragment.newInstance(roadMap),
                                R.id.main_frame_layout,
                                PasilleroFragment.TAG,
                                true
                            )
                        }

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

    override fun observeViewModel() {
        with(viewModel) {
            loadStopMapTruckList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    for (item in it.list) {
                        println("llista")
                        println("llista $item")
                        println("llista addressFk ${item.addressFk}")
                        println("llista id" + item.id)
                        println("llista address" + item.address)
                        println("llista client id" + item.address?.address?.client)
                        println("llista mobile " + item.address?.address?.mobile)
                    }
                    showRoadMapList(it)
                }
            }

        }
    }

    private fun showRoadMapList(it: RoadStopMapTruckList) {
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        originalList = it.list
        adapter = StopMapListAdapter(originalList,
            object : OnStopMapClickListener {

                @RequiresApi(Build.VERSION_CODES.Q)
                override fun onStopMapClickListener(
                    item: RoadStopMapTruck,
                    entryPoint: String,
                    action: TruckAction,
                    view: View?
                ) {
                    when (action) {
                        TruckAction.UNLOAD -> {

                            ma.addFragmentOnTop(
                                StopMapPalletListFragment.newInstance(
                                    title = item.description ?: "", item, action
                                )
                            )

                        }

                        TruckAction.LOAD -> {

                            ma.addFragmentOnTop(
                                StopMapPalletListFragment.newInstance(
                                    title = item.description ?: "", item, action
                                )
                            )

                        }

                        TruckAction.GOTOMAPS -> {
                            println("locationMaps")

                            val uri =
                                "geo:0,0?q=" + item.address?.address?.nickname + " " + item.address?.address?.street + " " + item.address?.address?.city + " " + item.address?.address?.postalCode
                            val locationIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
                            startActivity(locationIntent)
                        }

                        TruckAction.CALL -> {
                            showPhones(item)
                        }

                        TruckAction.OPTIONS -> {
                            val popupMenu = PopupMenu(requireContext(), view, Gravity.END)
                            popupMenu.inflate(R.menu.menu_options)
                            popupMenu.setForceShowIcon(true)

                            popupMenu.setOnMenuItemClickListener { itemOption ->
                                when (itemOption.itemId) {
                                    R.id.maps -> {
                                        val uri: String

                                        if (item.address?.address?.street != null) {
                                            uri =
                                                "geo:0,0?q=" + item.address?.address?.nickname + " " + item.address?.address?.street + " " + item.address?.address?.city + " " + item.address?.address?.postalCode
                                            val locationIntent =
                                                Intent(Intent.ACTION_VIEW, Uri.parse(uri))
                                            startActivity(locationIntent)
                                        } else {
                                            if (item.address?.address?.latitude == null || item.address?.address?.longitude == null) {
                                                getString(R.string.errorLocation).toast(
                                                    requireContext()
                                                )
                                            } else {
                                                uri =
                                                    "geo:${item.address?.address?.latitude},${item.address?.address?.longitude}"
                                                val locationIntent =
                                                    Intent(Intent.ACTION_VIEW, Uri.parse(uri))
                                                startActivity(locationIntent)
                                            }
                                        }

                                        true

                                    }

                                    R.id.call -> {
                                        showPhones(item)
                                        true
                                    }

                                    else -> false
                                }
                            }
                            popupMenu.show()
                        }

                    }

                }

            })
        binding.stopmapTruckRecyclerview.adapter = adapter
        binding.stopmapTruckRecyclerview.layoutManager = lm
        setFilter()

    }

    private fun showPhones(item: RoadStopMapTruck) {
        val customDialogList = CustomDialogList(requireContext())

        val phones: MutableList<GeneralItem> = mutableListOf()
        //Tarea 6275
        if (!item.address?.address?.mobile.isNullOrBlank()) {
            phones.add(
                GeneralItem(
                    text = "${item.address?.address?.mobile}",
                    code = item.address?.address?.mobile
                )
            )
        }
        if (!item.address?.address?.phone.isNullOrBlank()) {
            phones.add(
                GeneralItem(
                    text = "${item.address?.address?.phone}",
                    code = item.address?.address?.phone
                )
            )
        }
        if (!item.address?.address?.client?.phone.isNullOrBlank()) {
            phones.add(
                GeneralItem(
                    text = "${item.address?.address?.client?.phone}",
                    code = item.address?.address?.client?.phone
                )
            )
        }


        customDialogList.setValueVisibility(View.GONE)
        customDialogList.setTitle(getString(R.string.phones)).setKoButton(
            getString(
                R.string.cancel
            )
        ) {
            customDialogList.dismiss()
        }.hideDialog().show()

        val listPhonesAdapter = GeneralAdapter(phones, object : OnGeneralItemRowClickListener {
            override fun onGeneralItemRowClickListener(item: GeneralItem) {
                phones.forEach {
                    if (it.code == item.code) {
                        if (ContextCompat.checkSelfPermission(
                                requireContext(), Manifest.permission.CALL_PHONE
                            ) == PackageManager.PERMISSION_GRANTED
                        ) {
                            val callIntent = Intent(Intent.ACTION_CALL)
                            callIntent.data = Uri.parse("tel:${it.code}")
                            startActivity(callIntent)
                            return@forEach

                        }
                    } else {
                        ActivityCompat.requestPermissions(
                            context as Activity,
                            arrayOf(Manifest.permission.CALL_PHONE),
                            REQUEST_CALL_PERMISSION
                        )
                    }
                    customDialogList.dismiss()
                }
            }

        })

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

    }

}