package com.isidroid.c23.ui.screen.map._components

import android.Manifest
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.ContextCompat
import com.isidroid.c23.R
import com.isidroid.c23.ui.screen.map.MapContract
import rememberPermissionState

@Composable
internal fun RequestLocationPermissionComponent(state: State<MapContract.State>, onGranted: () -> Unit) {
    if (!state.value.requestLocationPermission)
        return

    val context = LocalContext.current
    val permission = Manifest.permission.ACCESS_FINE_LOCATION
    val hasPermission = ContextCompat.checkSelfPermission(context, permission) == android.content.pm.PackageManager.PERMISSION_GRANTED
    if (hasPermission) return

    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { if (it) onGranted() }

    val permissionState = rememberPermissionState(permission, launcher)
    if (permissionState.hasPermission) return

    if (permissionState.shouldShowRationale)
        LocationRationalDialog { permissionState.launchPermissionRequest() }
    else {
        LaunchedEffect(Unit) {
            permissionState.launchPermissionRequest()
        }
    }
}

@Composable
private fun LocationRationalDialog(onGrant: () -> Unit) {
    AlertDialog(
        title = { Text(text = stringResource(id = R.string.label_permission_rationale)) },
        text = { Text(text = stringResource(id = R.string.permission_rationale_message)) },
        onDismissRequest = { },
        confirmButton = {
            TextButton(onClick = onGrant) {
                Text(stringResource(id = R.string.action_grant_permissions))
            }
        }
    )
}

@Composable
@Preview
fun LocationRationalDialogPreview() {
    Surface {
        LocationRationalDialog {}
    }
}