package com.example.smart119.views

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.viewModels
import com.example.smart119.API_Helper
import com.example.smart119.AlertDialogUtil
import com.example.smart119.R
import com.example.smart119.TransferManager
import com.example.smart119.TransferState
import com.example.smart119.datas.HospitalSearch
import com.example.smart119.interfaces.RetrofitClient
import com.example.smart119.viewModel.TransferViewModel
import com.example.smart119.views.HospitalInfoPopup.showPopupTransfer
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.gson.JsonObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


/**
 * A simple [Fragment] subclass.
 * Use the [TransferFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class TransferFragment : Fragment() {
    // TODO: Rename and change types of parameters


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        TransferManager.registerListener("transfer_update_event", { data ->
//            println("Transfer Update Event!!!")
//        })
//        TransferManager.registerListener("transfer_update_event", ::TransferUpdateEvent)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_transfer, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        FragmentHandler.registerView("TransferFragment", view)

//        var tvHospName = view.findViewById<TextView>(R.id.tvTFHospName)
//        tvHospName.text = "서울특별시서남병원"
        
        // 카카오 길찾기 API
//        val src_pos = "126.705098, 37.412087";
//        val dst_pos = "126.696239, 37.395276";
//            RetrofitClient.pathInstance.findPath(
//                API_Helper.make_findpath_param(src_pos, dst_pos)
//            ).enqueue(findPathResponse())

        try {
            if (TransferManager.getState() == TransferState.STARTED) {
                TransferManager.SetLastHospitalInfo()
            }
        } catch (e: Exception) {
            println(e.message)
        }

        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // 뒤로 가기 동작 막음
//                println("Transfer 뒤로가기클릭!!")
            }
        })

        view.findViewById<Button>(R.id.transferCancel).setOnClickListener {
            AlertDialogUtil.showAlert(
                context = requireActivity(),
                title = "이송 취소",
                message = "이송을 취소하시겠습니까?",
                onPositiveClick = {
//                    val bottomNaviView = requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navigation)
//                    bottomNaviView.selectedItemId = R.id.hospSearch;
                    TransferManager.cancelTransfer()
                },
                onNegativeClick = {
                }
            )
        }

        view.findViewById<Button>(R.id.transferComplete).setOnClickListener {
            AlertDialogUtil.showAlert(
                context = requireActivity(),
                title = "이송 완료",
                message = "이송을 종료하시겠습니까?",
                onPositiveClick = {
                    val bottomNaviView = requireActivity().findViewById<BottomNavigationView>(R.id.bottom_navigation)
                    bottomNaviView.selectedItemId = R.id.hospSearch;
                    TransferManager.completeTransfer()
                },
                onNegativeClick = {}
            )
        }

        view.findViewById<Button>(R.id.btnTFDetailInfo).setOnClickListener {
            HospitalInfoPopup.showPopupTransfer(it)
            var getHPID = HospitalSearch.getHospitalID()
            if (!getHPID.isEmpty()) {
                try {
                    LoadingDialog.showDlg(requireContext())
                    var reqBody = API_Helper.make_detail_hosp_param(getHPID)
                    RetrofitClient.hospitalInstance.getDetail(reqBody).enqueue(hospDetailResponse())
                    HospitalInfoPopup.showPopupTransfer(it)
                } catch (e: Exception) {
                    println(e.message)
                } finally {
                    LoadingDialog.hideDlg()
                }
            }
        }

    }

    private fun hospDetailResponse(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                LoadingDialog.hideDlg()
                if (response.isSuccessful) {
                    val resObj = response.body();
                    //println(resObj)
                    /*
                    val metaObj = resObj?.get("meta");
                    if (metaObj != null) {
                        val tot_count = metaObj.asJsonObject["total_count"].asInt
                        if (tot_count > 0) {
                            var hsfView = FragmentHandler.getView("HospitalSearchFragment")
                            if (hsfView != null) {

                                val docus = resObj.getAsJsonArray("documents")
                                val addObj = docus[0].asJsonObject["address"];
                                val add_full = addObj.asJsonObject["address_name"]
                                val add_si = addObj.asJsonObject["region_1depth_name"]
                                val add_gu = addObj.asJsonObject["region_2depth_name"]
                                val add_dong = addObj.asJsonObject["region_3depth_name"]

                                var geoTv = hsfView.findViewById<TextView>(R.id.tvGeoLocation)
                                geoTv.text = add_full.asString;

                                HospitalSearch.set_gps_update(add_full.asString)
                            }
                        }
                    }
                    */
                    //response.body()["meta"].asJsonObject["total_count"]
                } else {
                    println("hospital detail not found")
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                LoadingDialog.hideDlg()
                println(t.message)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        // View를 Registry에서 제거

        FragmentHandler.unregisterView("TransferFragment")

    }

}