package com.example.doctor.Setting.Courses.EditCourses

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.example.doctor.Adapter.VpAdapter
import com.example.doctor.Auth.AuthActivity
import com.example.doctor.CodeError.Code429Activity
import com.example.doctor.CodeError.Code500Activity
import com.example.doctor.DoctorViewModel
import com.example.doctor.Enternet.EnternetActivity
import com.example.doctor.Enternet.EnternetFragment
import com.example.doctor.Pref.ClearPref
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.Pref.SavePref
import com.example.doctor.R
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.Setting.Courses.Adapter.CoursesDoctorAdapter
import com.example.doctor.Setting.Courses.EditCourses.TabLayoutEditCourses.AllSportCoursesDoctorFragment
import com.example.doctor.Setting.Courses.EditCourses.TabLayoutEditCourses.YourSportCoursesDoctorFragment
import com.example.doctor.Setting.Courses.Model.CoursesDoctorModel
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.FragmentCreateCoursesBinding
import com.google.android.material.tabs.TabLayoutMediator
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 CreateCoursesFragment : Fragment(),CoursesDoctorAdapter.Listener {
    private lateinit var binding: FragmentCreateCoursesBinding
    private val model: DoctorViewModel by activityViewModels()
    private lateinit var doctorApi: DoctorApi
    lateinit var adapter: CoursesDoctorAdapter
    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()
    val prefDoctorSave = SavePref()





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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.apply {
            initRcView()

            GetCoursesDoctor()
            button()

            CLCreate.visibility = View.GONE

            btnCreateCourses.setOnClickListener{
                CLCreate.visibility = View.VISIBLE
            }

            //Закрытие экоана создания названия
            CLCreate.setOnClickListener{
                CLCreate.visibility = View.GONE
            }
            btnExitCreat.setOnClickListener{
                CLCreate.visibility = View.GONE
            }

//            CLEditCourses.setOnClickListener {
//                CLEditCourses.visibility = View.GONE
//            }


            btnExit.setOnClickListener{
               activity?.finish()
            }




            model.CoursesDoctorList.observe(viewLifecycleOwner) {
                adapter.submitList(it)
            }


            btnCreateCoursrsDoctor.setOnClickListener{
                CreateCoursesDoctor()
            }



        }
    }



    private fun CreateCoursesDoctor() {
        val name = binding.edCoursesDoctorName.text.toString()
        val description = binding.edCoursesDoctorDescription.text.toString()
        if(name!="" && description !=""){
            AddCoursesName(name,description)
        }
        else{
            Toast(requireContext()).showCustomInfoToast("Не все поля заполнены", requireActivity())
        }

    }

    private fun button() = with(binding){
        CVCardCreateCourses.setOnClickListener {

        }
//        CVEditCourses.setOnClickListener {
//
//        }
    }

    //Получения списка пациентов
    fun AddCoursesName(name:String,description:String) {
        if (isOnline(requireContext())) {
            visibleLoadYes()
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listCreateCoursesDoctor = doctorApi.AddCoursesName("Bearer $Tokens",name,description)

                requireActivity().runOnUiThread {



                    //Фиксируем полученные данные
                    val List = listCreateCoursesDoctor.body()
                    val Nice = listCreateCoursesDoctor.isSuccessful
                    val Code = listCreateCoursesDoctor.code()
                    if(Code==429){
                        val intetn = Intent(requireContext(), Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                Toast(requireContext()).showCustomInfoToast(List.message, requireActivity())
                                GetCoursesDoctor()
                            }
                        }
                    }
                    else if (Code == 500) {
                        val intetn = Intent(requireContext(), Code500Activity::class.java)

                        startActivity(intetn)
                    }
                    else if (Code == 401) {
                        val intetn = Intent(requireContext(), AuthActivity::class.java)
                        activity?.finish()
                        startActivity(intetn)
                    }
                    visibleLoadNo()
                }

            }
        } else {
            val intetn = Intent(requireContext(), EnternetActivity::class.java)
            activity?.finish()
            startActivity(intetn)
        }

    }
    //Получения списка курсов созданных доктором
    fun GetCoursesDoctor() {
        if (isOnline(requireContext())) {
            visibleLoadYes()
            initRetrofit()
            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
            CoroutineScope(Dispatchers.IO).launch {
                val listCoursesDoctor = doctorApi.GetCoursesDoctor("Bearer $Tokens")

                requireActivity().runOnUiThread {



                    //Фиксируем полученные данные
                    val List = listCoursesDoctor.body()
                    val Nice = listCoursesDoctor.isSuccessful
                    val Code = listCoursesDoctor.code()
                    if(Code==429){
                        val intetn = Intent(requireContext(), Code429Activity::class.java)

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                model.CoursesDoctorList.value = List.sport_courses_doctor
                                binding.txtNull.visibility = View.GONE
                            }
                        }
                    }
                    else if (Code == 500) {
                        val intetn = Intent(requireContext(), Code500Activity::class.java)

                        startActivity(intetn)
                    }
                    else if (Code == 401) {
                        val intetn = Intent(requireContext(), AuthActivity::class.java)
                        activity?.finish()
                        startActivity(intetn)
                    }


                    visibleLoadNo()
                }

            }
        } else {
            val intetn = Intent(requireContext(), EnternetActivity::class.java)
            activity?.finish()
            startActivity(intetn)
        }

    }

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

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

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

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

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

    }


    fun visible1()=with(binding){
        constraintLayout2.visibility = View.VISIBLE
        CLCreate.visibility = View.GONE
      //  CLEditCourses.visibility = View.GONE
        CLLoad.visibility = View.GONE
    }
    fun visible2()=with(binding){
        constraintLayout2.visibility = View.GONE
        CLCreate.visibility = View.VISIBLE
        //CLEditCourses.visibility = View.GONE
        CLLoad.visibility = View.GONE
    }

    fun visible3()=with(binding){
        constraintLayout2.visibility = View.GONE
        CLCreate.visibility = View.GONE
     //   CLEditCourses.visibility = View.VISIBLE
        CLLoad.visibility = View.GONE
    }

    fun visibleLoadYes()=with(binding){
        CLLoad.visibility = View.VISIBLE
    }
    fun visibleLoadNo()=with(binding){
        CLLoad.visibility = View.GONE
    }
    companion object {

        fun newInstance() = CreateCoursesFragment()
    }
//    //Получения списка курсов созданных доктором
//    fun GetEditCourseDoctorAll(id:Int) {
//        if (isOnline(requireContext())) {
//            initRetrofit()
//            val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
//            CoroutineScope(Dispatchers.IO).launch {
//                val listCoursesDoctor = doctorApi.GetEditCourseDoctorAll("Bearer $Tokens",id)
//
//                requireActivity().runOnUiThread {
//
//                    //Фиксируем полученные данные
//                    val CoursesDoctorList = listCoursesDoctor.body()
//
//                    //Если нету ошибок
//                    if (CoursesDoctorList != null) {
//                        model.EditCoursesDoctorAllList.value = CoursesDoctorList.set_of_sports_exercises_all
//                        binding.txtNull.visibility = View.GONE
//                    }
//                    else{
//                        binding.txtNull.visibility = View.VISIBLE
//                    }
//
//                }
//
//            }
//        } else {
//            val intetn = Intent(requireContext(), EnternetActivity::class.java)
//            activity?.finish()
//            startActivity(intetn)
//        }
//
//    }
//    //Получения списка курсов созданных доктором
//    fun GetEditCourseDoctorYour(id:Int) {
//        if (isOnline(requireContext())) {
//        initRetrofit()
//        val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
//        CoroutineScope(Dispatchers.IO).launch {
//            val listCoursesDoctor = doctorApi.GetEditCourseDoctorYour("Bearer $Tokens",id)
//
//            requireActivity().runOnUiThread {
//
//                //Фиксируем полученные данные
//                val CoursesDoctorList = listCoursesDoctor.body()
//
//                //Если нету ошибок
//                if (CoursesDoctorList != null) {
//                    model.EditCoursesDoctorYourList.value = CoursesDoctorList.set_of_sports_exercises_your
//                }
//            }
//        }
//    } else {
//            val intetn = Intent(requireContext(), EnternetActivity::class.java)
//            activity?.finish()
//            startActivity(intetn)
//    }
//
//    }



    //Проверка интернета
    fun isOnline(context: Context): Boolean {
        if (context == null) return false
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val capabilities =
                connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
            if (capabilities != null) {
                when {
                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                        return true
                    }

                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                        return true
                    }

                    capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                        return true
                    }
                }
            }
        } else {
            val activeNetworkInfo = connectivityManager.activeNetworkInfo
            if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
                return true
            }
        }
        return false
    }
    override fun onClickCourses(item: CoursesDoctorModel){
//       // CLEditCourses.visibility = View.VISIBLE
//        prefDoctorSave.saveIdCourses(requireContext(),item.id)
//        prefDoctorSave.saveIdActivitis(requireContext(),item.id_activity)
//     //   model.CoursesDoctorCA.value= CoursesDoctorCA(item.id,item.id_activity)
//        GetEditCourseDoctorAll(item.id)
//        GetEditCourseDoctorYour(item.id)

        model.CoursesCustomDoctor.value = item
        activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLCoursesActivity, EditCoursesFragment.newInstance())?.commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем

    }
}