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

import android.app.AlertDialog
import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.DatePicker
import android.widget.EditText
import android.widget.TimePicker
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentRoadmapSettingsBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnRoadMapClickListener
import es.verdnatura.presentation.view.feature.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.roadmap.adapter.RoadMapListAdapter
import es.verdnatura.presentation.view.feature.roadmap.model.RoadMapTruck
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Calendar

class RoadMapSettingsFragment(
    private var roadMap: RoadMapTruck
) : BaseFragment<FragmentRoadmapSettingsBinding, RoadMapListViewModel>(
    RoadMapListViewModel::class
) {

    private var adapter: RoadMapListAdapter? = null
    private var onRoadMapClickListener: OnRoadMapClickListener? = null
    private var originalList = listOf<RoadMapTruck>()

    companion object {
        fun newInstance(roadMap: RoadMapTruck) = RoadMapSettingsFragment(roadMap)
    }

    override fun onAttach(context: Context) {
        if (context is OnRoadMapClickListener) onRoadMapClickListener = context
        super.onAttach(context)
    }

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

    override fun init() {

        binding.mainToolbar.toolbarTitle.text = roadMap.trailerPlate
        //LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))
        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        setToolBar()
        setEventsCliks()
        viewModel.roadMapTruckList(filter = """{"where": { "id": ${roadMap.id}}}""")
        super.init()
    }

    private fun setEventsCliks() {
        binding.saveButton.setOnClickListener {

            val myRoadMap = RoadMapTruck(
                id = roadMap.id,
                driverName = roadMap.driverName,
                trailerPlate = roadMap.trailerPlate,
                observations = roadMap.observations,
                kmStart = binding.kmStart.text?.takeIf { it.isNotBlank() }?.toString()
                    ?.toInt(),
                kmEnd = binding.kmEnd.text?.takeIf { it.isNotBlank() }?.toString()?.toInt()
            )
            myRoadMap.started = binding.dateInit.text?.takeIf { it.isNotBlank() }?.toString()
            myRoadMap.finished = binding.dateEnd.text?.takeIf { it.isNotBlank() }?.toString()

            viewModel.roadMapUpdate(
                roadMap.id, myRoadMap
            )
        }


        binding.dateInit.setOnFocusChangeListener { _, b ->
            if (b) {
                showDatePickerDialog(requireContext(), binding.dateInit) { year, month, day ->
                    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    val localDate = LocalDate.of(
                        year, month, day
                    )
                    binding.dateInit.setText(localDate.format(formatter).toString())
                }
            }

        }
        binding.dateEnd.setOnFocusChangeListener { _, b ->
            if (b) {
                showDatePickerDialog(requireContext(), binding.dateEnd) { year, month, day ->
                    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                    val localDate = LocalDate.of(
                        year, month, day
                    )
                    binding.dateEnd.setText(localDate.format(formatter).toString())

                }
            }

        }


        binding.dateEnd.setOnClickListener {
            binding.textClock.showContextMenu()
        }
    }

    private fun setRoadMap(roadMap: RoadMapTruck) {
        binding.kmStart.setText(roadMap.kmStart?.toString() ?: "")
        binding.kmEnd.setText(roadMap.kmEnd?.toString() ?: "")
        binding.dateInit.setText(roadMap.started ?: "")
        binding.dateEnd.setText(roadMap.finished ?: "")

    }

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

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

                        iconReload -> {
                            //    viewModel.roadMapTruckList($road)
                        }
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    override fun observeViewModel() {
        with(viewModel) {
            responseUpdate.observe(viewLifecycleOwner) {
                ma.onMyBackPressed()
            }

            loadRoadMapTruckList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull { setRoadMap(it.list[0]) }
            }

        }
    }

    private fun showDatePickerDialog(
        context: Context, editTextSelected: EditText, onDateSelected: (Int, Int, Int) -> Unit
    ) {
        val calendar = Calendar.getInstance()
        val initialYear = calendar[Calendar.YEAR]
        val initialMonth = calendar[Calendar.MONTH]
        val initialDay = calendar[Calendar.DAY_OF_MONTH]

        val datePicker = DatePicker(context)
        datePicker.init(
            initialYear, initialMonth, initialDay
        ) { _, year, monthOfYear, dayOfMonth ->
            onDateSelected(
                year, monthOfYear + 1, dayOfMonth
            )
        }

        val builder = AlertDialog.Builder(context).setTitle(getString(R.string.selectDate))
            .setView(datePicker)
            .setPositiveButton(getString(R.string.accept)) { _, _ ->

                showTimePickerDialog(requireContext(), editTextSelected) { hour, minute ->
                    editTextSelected.setText(
                        getString(
                            R.string.dateTime,
                            editTextSelected.text,
                            hour,
                            minute
                        )
                    )

                }
            }.setNegativeButton(getString(R.string.cancel)) { _, _ ->
                editTextSelected.setText("")
            }

        val dialog = builder.create()
        dialog.show()
    }

    private fun showTimePickerDialog(
        context: Context,
        editTextSelected: EditText,
        onTimeSelected: (Int, Int) -> Unit
    ) {

        val timePicker = TimePicker(context)

        timePicker.setIs24HourView(true)
        timePicker.setOnTimeChangedListener { _, hour, minute ->
            onTimeSelected(hour, minute)
        }

        val builder = AlertDialog.Builder(context).setTitle(getString(R.string.selectHour))
            .setView(timePicker)
            .setPositiveButton(getString(R.string.accept)) { _, _ ->

            }
            .setNegativeButton(getString(R.string.cancel)) { _, _ ->
                editTextSelected.setText("")

            }

        val dialog = builder.create()
        dialog.show()
    }

}