package com.example.wabi.view.screeens.profile

import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.example.wabi.domain.navigation.NavigationProvider
import com.example.wabi.domain.navigation.Routes
import com.example.wabi.domain.repository.PrefManager
import com.example.wabi.domain.repository.UserShareDate
import com.example.wabi.domain.supabase.SupabaseServiceImpl
import com.example.wabi.models.supabase.User
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ProfileViewModel @Inject constructor(
    private val supabase: SupabaseServiceImpl, private val nav: NavigationProvider
) : ViewModel() {

    private val _currentUser = mutableStateOf(User())
    val currentUser: User get() = _currentUser.value

    fun updateDataCurrentUser(newData: User) {
        _currentUser.value = newData
    }

    fun getUser() {
        viewModelScope.launch {
            val user = supabase.getCurrentUser()

            if (user != null) {
                val response = supabase.getUserData(userId = user.id)
                if (response.error == "") {
                    _currentUser.value = response.user
                    PrefManager.userTheme = _currentUser.value.theme
                } else {
                    Log.d("profile", "data don't got")
                    Toast.makeText(
                        UserShareDate.context!!,
                        "Данные пользователя\nполучить не удалось",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
    }

    fun signOutCurrentUser(navController: NavHostController) {
        viewModelScope.launch {
            supabase.signOut()
            PrefManager.initPrefManager(UserShareDate.context!!)
            PrefManager.clearDataCurrentUser()
            UserShareDate.userIsLogging.value = false
            nav.goToNextScreen(navHostController = navController, Routes.PROFILE, Routes.PROFILE)
        }
    }
}