package com.example.doctor.Auth

import android.annotation.SuppressLint
import android.content.Intent
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.activityViewModels
import com.example.doctor.Auth.Model.AuthModel
import com.example.doctor.Auth.Model.UserModel
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.EnternetCheck
import com.example.doctor.MainActivity
import com.example.doctor.Pref.ClearPref
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.R
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.Pref.SavePref
import com.example.doctor.Toast.showCustomDangerToast
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.FragmentAuthBinding
import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create


class AuthFragment : Fragment() {

    private lateinit var binding: FragmentAuthBinding
    private lateinit var doctorApi: DoctorApi
    private val DoctorviewModel: DoctorViewModel by activityViewModels()

    //private var prefToken: SharedPreferences? = null
    private var Token = ""
    val prefDoctorSave = SavePref()
    val prefDoctorConclusion = ConclusionPref()
    val prefDoctorClear = ClearPref()

    //Класс проверки интеренета
    val enternetCheck = EnternetCheck()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentAuthBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    @SuppressLint("SuspiciousIndentation")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initRetrofit()

        prefDoctorClear.clearToken(requireContext())
        Token = prefDoctorConclusion.conclusionToken(requireContext())

        binding.apply {
            binding.textError.text = ""

                //Авторизоваться
                binding.btnAuth.setOnClickListener {
                    if(edLogin.text.toString() == ""||edPassword.text.toString() == ""){
                        Toast(requireContext()).showCustomInfoToast(
                            "Не все поля заполнены",
                            requireActivity()
                        )
                    }
                    else{
                    Auth(
                        AuthModel(
                            edLogin.text.toString(),
                            edPassword.text.toString(),
                        )
                    )
                }
            }
        }
    }



    private fun Auth(authModel: AuthModel) {
        if (enternetCheck.isOnline(requireContext())) {
            initRetrofit()
            CoroutineScope(Dispatchers.IO).launch {
                val response = doctorApi.LoginDoctor(authModel)
                val errorMessage = response.errorBody()?.string()
                    ?.let { JSONObject(it).getString("error") }//JSONObject(response.errorBody()?.string())
                requireActivity().runOnUiThread {

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

                        startActivity(intetn)
                    }
                    else if(Code==200) {
                        //Если нету ошибок
                        if (Nice) {
                            if (List != null) {
                                    DoctorviewModel.token.value = List.token
                                    prefDoctorSave.saveToken(requireContext(), List.token)

                                    val intetn = Intent(requireContext(), MainActivity::class.java)
                                    startActivity(intetn)
                                    activity?.finish()
                            }
                            else{
                                Toast(requireContext()).showCustomInfoToast(
                                    "Такого пользователя нету",
                                    requireActivity()
                                )
                            }
                        }
                    }
                    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)
                    }


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

    }


    //Инициализируем 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)

    }



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