package com.isidroid.c23.ui._component

import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
internal fun BackCloseComponent(navController: NavController) {
    var showExitApp by remember { mutableStateOf(false) }
    val activity = LocalContext.current as? ComponentActivity
    val scope = rememberCoroutineScope()

    LaunchedEffect(showExitApp) {
        if (showExitApp)
            scope.launch(Dispatchers.Default) {
                delay(2000)
                showExitApp = false
            }
    }

    BackHandler {
        when {
            navController.previousBackStackEntry != null -> navController.popBackStack()
            showExitApp -> activity?.finish()
            else -> {
                showExitApp = true
                Toast.makeText(activity, "Tap back again to close the app", Toast.LENGTH_LONG).show()
            }
        }
    }
}