package com.sambath.kunkhmer.screen.fighter

import android.app.DatePickerDialog
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.navigation.findNavController
import com.sambath.kunkhmer.R
import com.sambath.kunkhmer.app.App
import kotlinx.android.synthetic.main.fragment_fighter_admin.loadingProgressBar
import kotlinx.android.synthetic.main.fragment_fighter_admin.view.et_date
import kotlinx.android.synthetic.main.fragment_fighter_admin.view.et_desc
import kotlinx.android.synthetic.main.fragment_fighter_admin.view.et_title
import kotlinx.android.synthetic.main.fragment_fighter_admin.view.fighter_button
import kotlinx.android.synthetic.main.fragment_fighter_admin.view.spinner_fighter_1
import kotlinx.android.synthetic.main.fragment_fighter_admin.view.spinner_fighter_2
import kotlinx.android.synthetic.main.fragment_fighter_admin.view.submitButton
import java.text.SimpleDateFormat
import java.util.Calendar

class FighterAdminFragment : Fragment() {
    private var _root: View? = null
    private val binding get() = _root!!
    private lateinit var fighterViewModel: FighterViewModel
    private lateinit var selectedFighter1Id: String
    private lateinit var selectedFighter2Id: String

    private val calendar = Calendar.getInstance()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+0000")

    private final val fighter1 = "650d97d08cc32f66d67c0b60"
    private final val fighter2 = "650d98498cc32f66d67c0b65"
    private final val desc = "Keo Rumchong VS Thiago Teixeira"
    private final val title = "Keo Rumchong VS Thiago Teixeira"
    private final val date = "2023-10-30T12:55:04.395+0000"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _root = inflater.inflate(R.layout.fragment_fighter_admin, container, false)

        fighterViewModel = FighterViewModel(App.injectApiService(), App.injectPrefHelper())
        fighterViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            render(it)
        })
        fighterViewModel.getFighters()


        binding.et_date.setOnClickListener {
            showDatePickerDialog()
        }
        setDefaultData()

        binding.submitButton.setOnClickListener {
            loadingProgressBar.visibility = View.VISIBLE

            fighterViewModel.createMatch(
                binding.et_date.text.toString(),
                binding.et_title.text.toString(),
                binding.et_desc.text.toString(),
                listOf(selectedFighter1Id, selectedFighter2Id)
            )
        }

        binding.fighter_button.setOnClickListener {
            requireActivity().findNavController(R.id.nav_host_fragment_activity_main).navigate(R.id.navigation_create_fighter)
        }

        // Inflate the layout for this fragment
        return binding
    }

    private fun setDefaultData() {
        binding.et_title.setText("Keo Rumchong VS Thiago Teixeira")
        binding.et_desc.setText("Keo Rumchong VS Thiago Teixeira")
    }

    private fun showDatePickerDialog() {
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        val datePickerDialog = DatePickerDialog(
            requireContext(),
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                // Update the calendar with the selected date
                calendar.set(year, monthOfYear, dayOfMonth)

                // Format the selected date and update the EditText text
                val formattedDate = dateFormat.format(calendar.time)
                binding.et_date.setText(formattedDate)
            },
            year,
            month,
            day
        )

        datePickerDialog.show()
    }

    private fun render(state: FighterViewState) {
        if (state.isCreatedMatch) {
            Toast.makeText(context, "Create Success...", Toast.LENGTH_LONG).show()
            loadingProgressBar.visibility = View.GONE

            binding.et_date.setText("")
            binding.et_title.setText("")
            binding.et_desc.setText("")
        }

        if (state.isGetFighters) {
            val matchesData = state.fightersData!!
            // Ensure matches is not null before mapping
            val dropdownItems1 = matchesData.map { it.name  }

            val adapter1 = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, dropdownItems1)
            adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.spinner_fighter_1.adapter = adapter1
            binding.spinner_fighter_1.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parentView: AdapterView<*>, selectedItemView: View, position: Int, id: Long) {
                    //  Get the selected Matches object
                    val selectedMatch = matchesData[position]

                    // Access the corresponding ID (it.matchInfo.id)
                    selectedFighter1Id = selectedMatch.id
                }

                override fun onNothingSelected(parentView: AdapterView<*>) {
                    // Do nothing here
                }
            }
            //
            val dropdownItems2 = matchesData.map { it.name  }

            val adapter2 = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, dropdownItems2)
            adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.spinner_fighter_2.adapter = adapter2
            binding.spinner_fighter_2.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parentView: AdapterView<*>, selectedItemView: View, position: Int, id: Long) {
                    //  Get the selected Matches object
                    val selectedMatch = matchesData[position]

                    // Access the corresponding ID (it.matchInfo.id)
                    selectedFighter2Id = selectedMatch.id
                }

                override fun onNothingSelected(parentView: AdapterView<*>) {
                    // Do nothing here
                }
            }
        }
        // Other state handling...
    }
}