package com.safecheckin.app.ui.screens.contacts

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.safecheckin.app.data.model.Contact
import com.safecheckin.app.data.repository.CloudRepository
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

data class ContactsUiState(
    val contacts: List<Contact> = emptyList(),
    val isLoading: Boolean = false,
    val showAddDialog: Boolean = false,
    val editingContact: Contact? = null,
    val presetMessage: String = "",
    val errorMessage: String? = null,
    val successMessage: String? = null
)

/**
 * v1: 联系人全量走云端
 * - 进入页面从云端拉取
 * - 增删改操作完成后立即重新拉取云端数据
 * - 修复了 contact.id 可能为 null 导致空指针的 bug
 */
class ContactsViewModel(
    private val repository: CloudRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(ContactsUiState())
    val uiState: StateFlow<ContactsUiState> = _uiState.asStateFlow()

    init {
        loadData()
    }

    fun loadData() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val contacts = repository.getContacts()
                val presetMessage = repository.getPresetMessage()
                _uiState.update {
                    it.copy(
                        contacts = contacts,
                        presetMessage = presetMessage,
                        isLoading = false,
                        errorMessage = null
                    )
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.update {
                    it.copy(isLoading = false, errorMessage = "加载数据失败: ${e.message}")
                }
            }
        }
    }

    fun showAddDialog() {
        _uiState.update { it.copy(showAddDialog = true, editingContact = null, errorMessage = null, successMessage = null) }
    }

    fun hideAddDialog() {
        _uiState.update { it.copy(showAddDialog = false, editingContact = null, errorMessage = null, successMessage = null) }
    }

    fun editContact(contact: Contact) {
        _uiState.update { it.copy(showAddDialog = true, editingContact = contact, errorMessage = null, successMessage = null) }
    }

    fun saveContact(name: String, phone: String, email: String) {
        if (name.isBlank() || email.isBlank()) {
            _uiState.update { it.copy(errorMessage = "姓名和邮箱不能为空") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val editingContact = _uiState.value.editingContact
                val success = if (editingContact != null) {
                    // 编辑：先删除旧的（使用 toInt()，若 id 无效则跳过删除直接新增）
                    val oldId = editingContact.id.toInt()
                    if (oldId > 0) {
                        repository.deleteContact(oldId)
                    }
                    val newContact = editingContact.copy(name = name, phone = phone, email = email)
                    repository.insertContact(newContact)
                } else {
                    // 新增
                    repository.insertContact(Contact(name = name, phone = phone, email = email))
                }

                if (success) {
                    loadData()
                    hideAddDialog()
                    _uiState.update {
                        it.copy(successMessage = if (editingContact != null) "联系人已更新" else "联系人已添加")
                    }
                } else {
                    _uiState.update {
                        it.copy(isLoading = false, errorMessage = "保存联系人失败，请检查网络连接")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.update {
                    it.copy(isLoading = false, errorMessage = "保存联系人失败: ${e.message}")
                }
            }
        }
    }

    fun deleteContact(contact: Contact) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val contactId = contact.id.toInt()
                if (contactId <= 0) {
                    _uiState.update { it.copy(isLoading = false, errorMessage = "无效的联系人ID") }
                    return@launch
                }
                val success = repository.deleteContact(contactId)
                if (success) {
                    loadData()
                    _uiState.update { it.copy(successMessage = "联系人已删除") }
                } else {
                    _uiState.update { it.copy(isLoading = false, errorMessage = "删除联系人失败") }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.update {
                    it.copy(isLoading = false, errorMessage = "删除联系人失败: ${e.message}")
                }
            }
        }
    }

    /**
     * 更新预设遗言：上传至云端，成功后刷新本地 state
     */
    fun updatePresetMessage(message: String) {
        if (message.isBlank()) {
            _uiState.update { it.copy(errorMessage = "预设消息不能为空") }
            return
        }
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            try {
                val success = repository.setPresetMessage(message)
                if (success) {
                    _uiState.update {
                        it.copy(presetMessage = message, isLoading = false, successMessage = "预设消息已更新")
                    }
                } else {
                    _uiState.update { it.copy(isLoading = false, errorMessage = "更新预设消息失败") }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _uiState.update {
                    it.copy(isLoading = false, errorMessage = "更新预设消息失败: ${e.message}")
                }
            }
        }
    }

    fun clearMessages() {
        _uiState.update { it.copy(errorMessage = null, successMessage = null) }
    }

    class Factory(private val context: Context) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST")
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return ContactsViewModel(CloudRepository(context)) as T
        }
    }
}
