package com.example.tasks.screens

import androidx.compose.foundation.background
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.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.tasks.model.UserState
import com.example.tasks.navigation.Screen
import com.example.tasks.viewModels.AuthViewModel
import com.example.tasks.viewModels.DatabaseViewModel
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)
            viewModel.checkForRegistration()
        }
    }
    if (flag.value) {
        when (userState) {
            is UserState.Loading -> {
                Column(
                    Modifier
                        .fillMaxSize()
                        .background(Color(0xFF951DDD)),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Text(
                        text = "ДИКИЕ ЯГОДЫ",
                        fontWeight = FontWeight.Black,
                        fontSize = 30.sp,
                        color = Color.White
                    )
                }
            }

            is UserState.Success -> {
                if(viewModel.sellers.isEmpty()){
                    navController.navigate(Screen.AppNavigationCustomers.route)
                    flag.value = false
                }else{
                    navController.navigate(Screen.ProfileSeller.route)
                    flag.value = false
                }

            }

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