package com.example.tasks.screens

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.navigation.NavController
import com.example.tasks.model.UserState
import com.example.tasks.navigation.Screen
import com.example.tasks.viewModels.AuthViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

@Composable
fun Load(viewModel: AuthViewModel, navController: NavController) {
    val context = LocalContext.current
    val userState by viewModel.userState
    val flag = remember { mutableStateOf(true) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            viewModel.isUserLoggedIn(context)
        }
    }
    if (flag.value) {
        when (userState) {
            is UserState.Loading -> {
                Column(
                    Modifier.fillMaxSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Text("Хай")
                }
            }

            is UserState.Success -> {
                navController.navigate(Screen.Profile.route)
                flag.value = false
            }

            is UserState.Error -> {
                navController.navigate(Screen.Start.route)
                flag.value = false
            }
        }
    }
}