package com.isidroid.c23.ui.navigation.destinations

import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.isidroid.c23.ui.screen.details.JobDetailsContract
import com.isidroid.c23.ui.screen.details.JobDetailsScreen
import com.isidroid.c23.ui.screen.details.JobDetailsViewModel

@Composable
fun JobDetailsDestination(navController: NavHostController) {
    val viewModel: JobDetailsViewModel = hiltViewModel()
    val context = LocalContext.current

    JobDetailsScreen(
        state = viewModel.viewState,
        effectFlow = viewModel.effect,
        spotResultStateFlow = viewModel.spotResultStateFlow,
        onEventSent = { event -> viewModel.setEvent(event) },
        onNavigationRequested = { effect ->
            when (effect) {
                JobDetailsContract.Effect.Navigation.ToBack -> navController.popBackStack()
                is JobDetailsContract.Effect.Navigation.ToNavigationApp -> context.openGoogleMaps(lat = effect.lat, lng = effect.lng)
            }
        },
    )
}

private fun Context.openGoogleMaps(lat: Double?, lng: Double?) {
    if (lat == null || lng == null) return
    val gmmIntentUri = "geo:$lat,$lng".toUri()
    val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
//    mapIntent.setPackage("com.google.android.apps.maps")
    if (mapIntent.resolveActivity(packageManager) != null) {
        startActivity(mapIntent)
    } else {
        Toast.makeText(this, "Navigation app not found", Toast.LENGTH_LONG).show()
    }
}