package com.example.doctor.Patients

//noinspection SuspiciousImport
import android.R
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.example.doctor.DoctorViewModel
import com.example.doctor.Patients.Adapter.PatientListAdapter
import com.example.doctor.Patients.Model.PatientAllModel
import com.example.doctor.Patients.Model.PatientModel
import com.example.doctor.Patients.Reports.PatientFragment
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.databinding.FragmentPatientsListBinding
import com.example.user.BottomSheetMenu.NoteBottomSheetMenu
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


class PatientsListFragment : Fragment(), PatientListAdapter.Listener {
    private lateinit var binding: FragmentPatientsListBinding
    private val model: DoctorViewModel by activityViewModels()
    lateinit var adapterPatient: PatientListAdapter
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()



    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentPatientsListBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initRcViewDay()
        patientListCurrent()
        GetPatientList()




//        //Swipe down
//        binding.refreshLayout.setOnRefreshListener{
//            GetPatientList()
//            binding.refreshLayout.isRefreshing = false
//        }


        //Нажатие на кнопку заказать заказ
        binding.btnAddPatient.setOnClickListener {
            val noteBottomSheetMenu = NoteBottomSheetMenu.newInstance()
            noteBottomSheetMenu.show(
                requireActivity().supportFragmentManager,
                "Note Bottom Sheet Fragment"
            )
        }
    }

    //Получения списка пациентов
    fun GetPatientList() {
        initRetrofit()
        val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
        CoroutineScope(Dispatchers.IO).launch {
            val listProduct = doctorApi.GetPatientAll("Bearer $Tokens")
            requireActivity().runOnUiThread {

                //Фиксируем полученные данные
                val patientList = listProduct.body()

                //Если нету ошибок
                if (patientList != null) {
                    adapterPatient.submitList(patientList.patient)
                    //model.patientListList.value = patientList.PatientList
                    addListSerchPatient(patientList.patient)
                }
            }

        }
    }



    private fun addListSerchPatient(patient: List<PatientAllModel>) {
        val listPatient = arrayListOf("")
        for(i in 0 .. patient.count()-1){
            listPatient.add(patient[i].login.toString())
        }

        val adapter = ArrayAdapter(requireContext(), R.layout.simple_list_item_1, listPatient)
        binding.searchPatient.threshold = 1
        binding.searchPatient.setAdapter(adapter)

        binding.searchPatient.setOnItemClickListener { parent, arg1, pos, id ->
            //val list = ArrayList<PatientModel>()
            val serpat = binding.searchPatient.text.toString()

            //Вывод фрагмента на активити при первоначальной загрузке
            activity?.supportFragmentManager?.beginTransaction()
                ?.replace(com.example.doctor.R.id.CLMainListPatient, PatientFragment.newInstance())
                ?.commit()


            binding.CLMainListPatient2.visibility = View.GONE
            //Ищем пациента по логину
            for(i in 0 ..patient.count()-1) {
                if(patient[i].login == serpat){
                    model.patientCurrent.value = patient[i]
                }
            }


        }

    }

    //Вывод прогресса на один день
    private fun patientListCurrent() = with(binding) {
//        model.patientListCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
//
//        }

    }

    //Инициализируем Retrofit
    private fun initRetrofit() {
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        val client = OkHttpClient
            .Builder()
            .addInterceptor(interceptor)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl("http://mobileapp.vmeda.org/api/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        doctorApi = retrofit.create(DoctorApi::class.java)

    }

    //Инициализация списка
    private fun initRcViewDay() = with(binding) {
        rcView.layoutManager =
            GridLayoutManager(requireContext(), 1)//По вертикали будет выводить по умолчанию
        adapterPatient = PatientListAdapter(this@PatientsListFragment)
        rcView.adapter = adapterPatient
    }

    companion object {
        fun newInstance() = PatientsListFragment()
    }


    override fun onClickPatient(item: PatientAllModel) {
        //Вывод фрагмента на активити при первоначальной загрузке
        activity?.supportFragmentManager?.beginTransaction()
            ?.replace(com.example.doctor.R.id.CLMainListPatient, PatientFragment.newInstance())
            ?.commit()
        //binding.rcView.visibility = View.GONE
        binding.CLMainListPatient2.visibility = View.GONE
        model.patientCurrent.value = item

    }
}