package com.example.smart119

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import com.example.smart119.databinding.ActivityMainBinding
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.example.smart119.datas.HospitalSearch
import com.example.smart119.datas.SaveLogin
import com.example.smart119.interfaces.RetrofitClient
import com.example.smart119.viewModel.TransferViewModel
import com.example.smart119.views.LoadingDialog
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.textfield.TextInputEditText
import com.google.gson.JsonObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private val LOCATION_PERMISSION_REQUEST_CODE = 100
    private val viewModel by viewModels<TransferViewModel>()

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                // 권한이 허용되면 서비스 시작
                LocationHelper.startLocationService(this)
            } else {
                // 권한 거부됨 -> 필요한 안내 처리
            }
        }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

//        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        // 권한 요청 흐름 시작
//        if (!checkAndRequestLocationPermission()) {
//            return
//        }

//        LocationHelper.init(this, {
//            finish()
//        });
        LocationHelper.startLocationService(this)

        SaveLogin.init(this);
        HospitalSearch.init_hospital_req(this)


//        LocationHelper.getLastKnownLocation_TOASTMSG(this)

        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController

        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_navigation)
        bottomNavigationView.setupWithNavController(navController)

        //이송 초기화
        TransferManager.setIdle()

        //네비게이션하고 fragment 연결
        bottomNavigationView.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.emgLogin -> {
                    if (LoginManager.isLoggedIn()) {
                        val _inputId = SaveLogin.getUserId()
                        val _inputCarno = SaveLogin.getCarNo()
                        val message = """
                            현재 로그인된 정보입니다.                        
                            아이디: $_inputId
                            차량번호: $_inputCarno                        
                            로그아웃하시겠습니까?
                            
                        """.trimIndent()

                        AlertDialogUtil.showAlert(
                            context = this,
                            title = "로그인 상태 확인",
                            message = message,
                            onPositiveClick = {
                                //로그아웃 처리
                                println("logout")
                                navController.navigate(R.id.LoginFragment)
                                SaveLogin.setLogin(false)
                                TransferManager.clear_state()
                            },
                            onNegativeClick = {

                            }
                        )
                        false
                    }
                    else {
                        navController.navigate(R.id.LoginFragment)
                        true
                    }
                }
                R.id.hospSearch -> {
                    navController.navigate(R.id.HospSearchFragment)
                    true
                }
                R.id.hospTransfer -> {
                    navController.navigate(R.id.TransferFragment)
                    true
                }
                else -> false
            }
        }

        TransferManager.registerListener("transfer_update_event", ::TransferUpdateEvent)
        TransferManager.registerListener("transfer_dialogmsg_event", ::TransferDialogMsgEvent)

        MedicalInfo.init()

//        viewModel.requestData()
//        viewModel.someLiveData.observe(viewLifecycleOwner) { result ->
//            // UI 업데이트
//        }
    }
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration)
                || super.onSupportNavigateUp()
    }

    //권한 확인
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LocationHelper.handleGpsState(this)
            } else {
                // "다시 묻지 않음" 여부 확인
                if (!ActivityCompat.shouldShowRequestPermissionRationale(
                        this as Activity, Manifest.permission.ACCESS_FINE_LOCATION
                    )
                ) {
                    // 설정 화면으로 이동 안내(MainActivity에 구현)
                    showSettingsDialog(this@MainActivity) { finish() }
                } else {
                    Toast.makeText(this, "권한이 거부되었습니다. 앱을 종료합니다.", Toast.LENGTH_SHORT).show()
                    finish();
                }
            }
        }
        else {
            println("gps 권한 여부 코드 : ${requestCode}")
        }
    }

    private fun showSettingsDialog(activity: Activity, onFinish: () -> Unit) {
        AlertDialog.Builder(activity)
            .setTitle("권한 필요")
            .setMessage("위치 권한이 필요합니다. 설정에서 권한을 허용해주세요.")
            .setPositiveButton("설정으로 이동") { _, _ ->
                goToAppSettings(activity)
            }
            .setNegativeButton("취소") { _, _ ->
                Toast.makeText(activity, "권한이 거부되었습니다. 앱을 종료합니다.", Toast.LENGTH_SHORT).show()
                onFinish()
            }
            .show()
    }

    private fun goToAppSettings(activity: Activity) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package", activity.packageName, null)
        }
        activity.startActivity(intent)
    }

    private fun onAccessButtonClick() {
        Toast.makeText(this, "Button clicked!", Toast.LENGTH_SHORT).show()
    }


    fun TransferUpdateEvent(data: JsonObject?) {
    }

    fun TransferDialogMsgEvent(data: JsonObject?) {
        try {
            var _msgObj = data?.asJsonObject!!;

            AlertDialogUtil.showAlert(
                context = this,
                title = _msgObj["title"].toString().trim('"'),
                message = _msgObj["msg"].toString().trim('"'),
                onPositiveClick = {
                    val activity = AlertDialogUtil.getActivityContext()
                    val bottomNav = activity?.findViewById<BottomNavigationView>(R.id.bottom_navigation)
                    if (bottomNav != null &&
                        bottomNav.selectedItemId != R.id.hospSearch
                    ){
                        bottomNav.selectedItemId = R.id.hospSearch
                    }
                },
                onNegativeClick = {
                    val activity = AlertDialogUtil.getActivityContext()
                    val bottomNav = activity?.findViewById<BottomNavigationView>(R.id.bottom_navigation)
                    if (bottomNav != null &&
                        bottomNav.selectedItemId != R.id.hospSearch
                    ) {
                        bottomNav.selectedItemId = R.id.hospSearch
                    }
                }
            )
        } catch (e: Exception) {
            //TODO("Not yet implemented")
        }
    }

    //3. 권한 요청 코드
    private fun checkAndRequestLocationPermission(): Boolean {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
        ) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                )
            ) {
                // 권한 요청 설명
                showPermissionRationale()
            } else {
                // 권한 요청
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    LOCATION_PERMISSION_REQUEST_CODE
                )
            }
            return false
        }
        return true
    }

    private fun showPermissionRationale() {
        AlertDialog.Builder(this)
            .setTitle("위치 권한 필요")
            .setMessage("앱에서 정확한 위치 서비스를 제공하려면 위치 권한이 필요합니다.")
            .setPositiveButton("권한 허용") { _, _ ->
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                    LOCATION_PERMISSION_REQUEST_CODE
                )
            }
            .setNegativeButton("취소") { _, _ ->
                Toast.makeText(this, "권한이 거부되었습니다. 앱을 종료합니다.", Toast.LENGTH_SHORT).show()
                finish()
            }
            .show()
    }

    private fun showSettingsDialog() {
        AlertDialog.Builder(this)
            .setTitle("권한 필요")
            .setMessage("위치 권한이 필요합니다. 설정에서 권한을 허용해주세요.")
            .setPositiveButton("설정으로 이동") { _, _ ->
                goToAppSettings(this)
            }
            .setNegativeButton("취소") { _, _ ->
                Toast.makeText(this, "권한이 거부되었습니다. 앱을 종료합니다.", Toast.LENGTH_SHORT).show()
                finish()
            }
            .show()
    }

    //4. 설정 화면으로 이동
    fun goToAppSettings(context: Context) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package", context.packageName, null)
        }
        context.startActivity(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        LocationHelper.stopLocationService(this)
        TransferManager.clear_state();
    }
}