package com.example.user.BottomSheetMenu

import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.Color
import android.os.Bundle
import android.support.annotation.Nullable
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.Toast
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.activityViewModels
import com.example.doctor.DoctorViewModel
import com.example.doctor.Patients.Model.CreatePatientModel
import com.example.doctor.Pref.ConclusionPref
import com.example.doctor.R
import com.example.doctor.Retrofit.DoctorApi
import com.example.doctor.Toast.showCustomInfoToast
import com.example.doctor.databinding.ItemButtomMenuBinding
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
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 NoteBottomSheetMenu: BottomSheetDialogFragment() {
    private lateinit var binding: ItemButtomMenuBinding
    private lateinit var doctorApi: DoctorApi
    val prefDoctorConclusion = ConclusionPref()

    @SuppressLint("RestrictedApi")
    override fun setupDialog(dialog: Dialog, style: Int) {
        super.setupDialog(dialog, style)

        val view = LayoutInflater.from(context).inflate(R.layout.item_buttom_menu, null)
        dialog.setContentView(view)

        val param = (view.parent as View).layoutParams as CoordinatorLayout.LayoutParams

        val behavior = param.behavior

        if(behavior is BottomSheetBehavior<*>){
            behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback(){
                override fun onStateChanged(bottomSheet: View, newState: Int) {
                    var state = ""
                    when(newState){
                        BottomSheetBehavior.STATE_DRAGGING->{
                            state = "DRAGGING"
                        }
                        BottomSheetBehavior.STATE_SETTLING->{
                            state = "SETTLING"
                        }
                        BottomSheetBehavior.STATE_EXPANDED->{
                            state = "EXPANDED"
                        }
                        BottomSheetBehavior.STATE_COLLAPSED->{
                            state = "COLLAPSED"
                        }
                        BottomSheetBehavior.STATE_HIDDEN->{
                            state = "HIDDEN"
                            dismiss()
                            behavior.state = BottomSheetBehavior.STATE_COLLAPSED
                        }

                    }
                }

                override fun onSlide(bottomSheet: View, slideOffset: Float) {

                }

            })
        }
    }

    //Данная функция необходима чтобы убрать белый фон в нижнем всплывающем меню
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        return super.onCreateDialog(savedInstanceState).apply {
            // window?.setDimAmount(0.2f) // Set dim amount here
            setOnShowListener {
                val bottomSheet = findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout
                bottomSheet.setBackgroundResource(android.R.color.transparent)
            }
        }
    }


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




    companion object {

        fun newInstance(): NoteBottomSheetMenu {
            val args = Bundle()
            val fragment = NoteBottomSheetMenu()
            fragment.arguments = args
            return  fragment
        }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.btnAddPatient.setOnClickListener{
            if(binding.edEmail.text.toString() == "" && binding.edPassword.text.toString() == ""){
                Toast(requireContext()).showCustomInfoToast("Не все поля заполнены", requireActivity())
            }
            else{
                CreateAccountPatient(CreatePatientModel(binding.edEmail.text.toString(),binding.edPassword.text.toString()))
            }
        }
    }


    fun CreateAccountPatient(createPatientModel: CreatePatientModel) {
        initRetrofit()
        val Tokens = prefDoctorConclusion.conclusionToken(requireContext())
        CoroutineScope(Dispatchers.IO).launch {
            val listProduct = doctorApi.CreateAccountPatient("Bearer $Tokens",createPatientModel)
            requireActivity().runOnUiThread {

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

                //Если нету ошибок
                if (patientList != null) {
                    Toast(requireContext()).showCustomInfoToast("Аккаунт для пациента создан", requireActivity())
                    dismiss()//После нажатия закрываем
                }
                else{
                    Toast(requireContext()).showCustomInfoToast("Ошибка валидации", requireActivity())
                }
            }

        }
    }


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

    }

}