// ui/contact/ContactsViewModel.kt
package com.example.initiateaphonecallapp.ui.contact

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.initiateaphonecallapp.data.model.ApiContactsRequest
import com.example.initiateaphonecallapp.data.model.ApiContactsResponse
import com.example.initiateaphonecallapp.data.network.RetrofitClient
import com.example.initiateaphonecallapp.data.repository.ContactsRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ContactsViewModel(
) : ViewModel() {
    private val contactsRepository = ContactsRepository()

    private val _addContactResult = MutableStateFlow<ApiContactsResponse?>(null)
    val addContactResult: StateFlow<ApiContactsResponse?> = _addContactResult.asStateFlow()

    private val _contacts = MutableStateFlow<List<ApiContactsRequest>>(emptyList())
    val contacts: StateFlow<List<ApiContactsRequest>> = _contacts.asStateFlow()

    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()

    /**
     * 添加联系人
     * @param name 联系人姓名
     * @param phone 联系人电话
     */
    fun addContact(name: String, phone: String) {
        _isLoading.value = true
        _errorMessage.value = null
        _addContactResult.value = null

        viewModelScope.launch {
            val result = contactsRepository.addContact(name, phone)

            result
                .onSuccess { response ->
                    _addContactResult.value = response
                    if (response.code==200) {
                        _errorMessage.value = response.msg
                    }
                }
                .onFailure { exception ->
                    _errorMessage.value = exception.message ?: "添加联系人失败"
                }

            _isLoading.value = false
        }
    }

    /**
     * 加载联系人列表
     */
    fun loadContacts() {
        _isLoading.value = true
        _errorMessage.value = null

        viewModelScope.launch {
            val result = contactsRepository.listContacts()

            result
                .onSuccess { contactsList ->
                    _contacts.value = contactsList.data
                }
                .onFailure { exception ->
                    _errorMessage.value = exception.message ?: "加载联系人失败"
                }

            _isLoading.value = false
        }
    }

    /**
     * 清除添加联系人的结果
     */
    fun clearAddContactResult() {
        _addContactResult.value = null
    }

    /**
     * 清除错误消息
     */
    fun clearError() {
        _errorMessage.value = null
    }

    /**
     * 清除所有状态
     */
    fun clearAll() {
        _addContactResult.value = null
        _errorMessage.value = null
    }
}