package com.framework.mvvm.ui.screen

import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import com.framework.mvvm.mv.AdmViewModel
import com.framework.mvvm.ui.LocalNavHostController
import kotlinx.coroutines.delay
import org.kodein.di.compose.rememberInstance

@Composable
fun FlashScreen() {
    val vm by rememberInstance<AdmViewModel>()
    val nav = LocalNavHostController.current!!

    BoxWithConstraints(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {

        ConstraintLayout(getConstraints()) {
            Text(text = "禹", Modifier.layoutId("text1"), fontSize = 24.em)
            Text(text = "数", Modifier.layoutId("text2"), fontSize = 24.em)
            Text(text = "ADM", Modifier.layoutId("text3"), fontSize = 12.em)
        }

        LaunchedEffect("flash") {
            val users = vm.getUsers()
            delay(1500)

            if (users.isNotEmpty()) {
                nav.navigate("project") {
                    launchSingleTop = true
                    popUpTo("flash") { inclusive = true }
                }
            } else {
                nav.navigate("login") {
                    launchSingleTop = true
                    popUpTo("flash") { inclusive = true }
                }
            }
        }
    }
}

private fun getConstraints(): ConstraintSet {
    return ConstraintSet {
        val text1 = createRefFor("text1")
        val text2 = createRefFor("text2")
        val text3 = createRefFor("text3")

        constrain(text1) {
            top.linkTo(parent.top)
            bottom.linkTo(text2.top, margin = 16.dp)
            start.linkTo(parent.start)
            end.linkTo(parent.end)
        }
        constrain(text2) {
            top.linkTo(text1.bottom, margin = 16.dp)
            bottom.linkTo(text3.top, margin = 16.dp)
            start.linkTo(parent.start)
            end.linkTo(parent.end)
        }
        constrain(text3) {
            top.linkTo(text2.bottom, margin = 32.dp)
            bottom.linkTo(parent.bottom)
            start.linkTo(parent.start)
            end.linkTo(parent.end)
        }
    }
}