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.location.LocationManager
import android.net.Uri
import android.provider.Settings
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.gson.JsonObject

object LocationHelper {
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private val LOCATION_PERMISSION_REQUEST_CODE = 100

    // ✅ 실시간 위치 저장용 변수
    private var currentLat: Double = 0.0
    private var currentLon: Double = 0.0



    fun startLocationService(ctx: Context, onFinish: () -> Unit = {}) {
        if (!checkAndRequestLocationPermission(ctx, onFinish)) return

        if (!isGpsEnabled(ctx)) {
            promptEnableGps(ctx)
            return
        }

        val serviceIntent = Intent(ctx, LocationService::class.java)
        ContextCompat.startForegroundService(ctx, serviceIntent)
        println("[startLocationService] - start")
    }
    fun stopLocationService(ctx: Context) {
        val serviceIntent = Intent(ctx, LocationService::class.java)
        ctx.stopService(serviceIntent)
    }

    fun setCurrentLocation(lat: Double, lon: Double) {
        currentLat = lat
        currentLon = lon
    }

    fun getCurrentLat(): Double = currentLat
    fun getCurrentLon(): Double = currentLon

    fun init(
        ctx: Context,
        onFinish:() -> Unit
    ) {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(ctx)
        if (!checkAndRequestLocationPermission(ctx, onFinish)) {
            return
        }

        handleGpsState(ctx)
    }

    fun handleGpsState(ctx: Context) {
        if (isGpsEnabled(ctx)) {
            //Toast.makeText(this, "GPS is already enabled", Toast.LENGTH_SHORT).show()
            println("GPS Enabled")
            startLocationService(ctx)
        } else {
            println("GPS not Enabled")
            promptEnableGps(ctx)
        }
    }

//    fun permissionResultInvoke(
//        ctx: Context,
//        requestCode: Int,
//        permissions: Array<out String>,
//        grantResults: IntArray,
//        onFinish: () -> Unit
//    ) {
//        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
//            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                LocationHelper.handleGpsState(ctx)
//            } else {
//                // "다시 묻지 않음" 여부 확인
//                if (!ActivityCompat.shouldShowRequestPermissionRationale(
//                        ctx as Activity, Manifest.permission.ACCESS_FINE_LOCATION
//                    )
//                ) {
//                    // 설정 화면으로 이동 안내(MainActivity에 구현)
//                    showSettingsDialog(ctx, onFinish)
//                } else {
//                    Toast.makeText(ctx, "권한이 거부되었습니다. 앱을 종료합니다.", Toast.LENGTH_SHORT).show()
//                    onFinish();
//                }
//            }
//        }
//    }

    private fun showSettingsDialog(ctx: Context, onFinish: () -> Unit) {
        AlertDialog.Builder(ctx)
            .setTitle("권한 필요")
            .setMessage("위치 권한이 필요합니다. 설정에서 권한을 허용해주세요.")
            .setPositiveButton("설정으로 이동") { _, _ ->
                goToAppSettings(ctx)
            }
            .setNegativeButton("취소") { _, _ ->
                Toast.makeText(ctx, "권한이 거부되었습니다. 앱을 종료합니다.", Toast.LENGTH_SHORT).show()
                onFinish()
            }
            .show()
    }
    private fun goToAppSettings(context: Context) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package", context.packageName, null)
        }
        context.startActivity(intent)
    }

    //1.현재 gps 상태 확인
    private fun isGpsEnabled(ctx: Context): Boolean {
        val locationManager = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
    }

    //2.gps 활성화 요청
    private fun promptEnableGps(ctx: Context) {
        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
        ctx.startActivity(intent)
    }

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

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

}
