package com.laseroptek.raman.ui.screens.config.time

import android.content.Intent
import android.content.res.Configuration
import android.provider.Settings
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import timber.log.Timber

@Composable
fun TimeSettingPopup(
    onDismiss: () -> Unit = {}
) {
    val context = LocalContext.current

    // This launcher will be triggered when the settings activity is closed.
    val settingsLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) {
        // When we return from settings, just dismiss this popup.
        Timber.d("Returned from settings, dismissing TimeSettingPopup.")
        onDismiss()
    }

    // This is the key: Launch the settings screen immediately when this popup becomes visible.
    LaunchedEffect(Unit) {
        try {
            val intent = Intent(Settings.ACTION_DATE_SETTINGS).apply {
                addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
            }
            settingsLauncher.launch(intent)
        } catch (e: Exception) {
            Timber.e(e, "Could not open Date & Time settings")
            Toast.makeText(
                context,
                "Could not open Date & Time settings.",
                Toast.LENGTH_LONG
            ).show()
            // If it fails, dismiss the popup immediately.
            onDismiss()
        }
    }

    // Display a simple, full-screen, semi-transparent background.
    // This creates the new, isolated layout context.
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.6f)),
        contentAlignment = Alignment.Center
    ) {
        // You can optionally show a message here, but for a quick transition,
        // this can remain empty. The LaunchedEffect handles the logic.
        // Text("Redirecting to settings...", color = Color.White)
    }
}

@Preview(
    uiMode = Configuration.UI_MODE_NIGHT_NO,
    showBackground = false,
    device = "spec:width=1920dp,height=1080dp,dpi=150,isRound=false,chinSize=0dp,orientation=landscape"
)

@Composable
fun PreviewTimeSettingView() {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        TimeSettingPopup(onDismiss = {
            Timber.d("onDismiss")
        })
    }

}
