import android.Manifest
import android.content.Context
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.isidroid.c23.ui.theme.AppTheme
import com.isidroid.utils.hasPermission
import com.isidroid.utils.shouldShowRequestPermissionRationale

class PermissionState(
    private val permission: String,
    private val context: Context,
    private val permissionLauncher: ManagedActivityResultLauncher<String, Boolean>?
) {
    var hasPermission by mutableStateOf(context.hasPermission(permission))
        private set

    var shouldShowRationale by mutableStateOf(context.shouldShowRequestPermissionRationale(permission))
        private set

    fun launchPermissionRequest() {
        shouldShowRationale = context.shouldShowRequestPermissionRationale(permission)
        permissionLauncher?.launch(permission)
    }
}

@Composable
fun rememberPermissionState(
    permission: String,
    launcher: ManagedActivityResultLauncher<String, Boolean>? = null
): PermissionState {
    val context = LocalContext.current
    return remember(permission, context) {
        PermissionState(permission, context, launcher)
    }
}

@Composable
fun PermissionRequestScreen() {
    val permissionState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION)

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        if (permissionState.hasPermission) {
            Text("Permission Granted!")
        } else {
            if (permissionState.shouldShowRationale) {
                Text("We need access to your location for a better experience.")
            }

            Spacer(modifier = Modifier.height(16.dp))

            Button(onClick = {
                permissionState.launchPermissionRequest()
            }) {
                Text("Request Permission")
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    AppTheme {
        PermissionRequestScreen()
    }
}
