package com.example.wabi.view.screeens.signIn

import android.util.Log
import androidx.compose.runtime.MutableState
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.screens.SignInState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SignInViewModel @Inject constructor(
    private val supabase: SupabaseServiceImpl, private val nav: NavigationProvider
) : ViewModel() {
    private val _data = mutableStateOf(SignInState())
    val data: SignInState get() = _data.value

    fun updateData(newData: SignInState) {
        _data.value = newData
    }

    fun signIn(navController: NavHostController, printError: MutableState<Boolean>) {
        if (data.email != "" && data.password != "") {
            viewModelScope.launch {
                val response = supabase.signIn(_data.value.email, _data.value.password)
                if (response.error == "") {

                    UserShareDate.userIsLogging.value = true
                    printError.value = false

                    PrefManager.initPrefManager(UserShareDate.context!!)
                    PrefManager.saveDataCurrentUser(data.email, data.password)

                    nav.goToNextScreen(
                        navHostController = navController, Routes.SIGNIN, Routes.PROFILE
                    )
                } else {
                    Log.d("signIn", "Ошибка входа!")
                    printError.value = true
                }
            }
        }
    }

    fun validateEmail(email: String): Boolean {
        return email != "" && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()
    }
}