package com.example.wabi.view.screens.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.NavigationFun
import com.example.wabi.domain.navigation.Routes
import com.example.wabi.domain.network.SupabaseServiceImpl
import com.example.wabi.domain.repository.UserData
import com.example.wabi.model.screens.SignInState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SignInViewModel @Inject constructor(
    private val sup: SupabaseServiceImpl, private val nav: NavigationFun
) : 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 = sup.signIn(_data.value.email, _data.value.password)
                if (response.error == "") {
                    UserData.isSession.value = true
                    printError.value = false
                    nav.NextScreen(navController = navController, Routes.SIGNIN, Routes.BASKET)
                } else {
                    Log.d("signIn", "Ошибка входа!")
                    printError.value = true
                }
            }
        }
    }

    fun goToRegistration(navController: NavHostController) {
        viewModelScope.launch {
            nav.NextScreen(
                navController = navController, whereFrom = Routes.SIGNIN, where = Routes.SIGNUP
            )
        }
    }

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

    init {
        viewModelScope.launch {
            sup.singInWithOTP("chernoff.serg3i@yandex.ru")
        }
    }

}