import Foundation
import SwiftUI

@Observable
final class ProfileViewModel {
    var profile: UserProfile?
    var avatarData: Data?
    var isLoading = false
    var isSaving = false
    var errorMessage: String?

    // Editable fields
    var phone = ""
    var phoneVisible = false
    var location = ""
    var locationVisible = false

    func loadProfile(userId: String? = nil, chatClient: ChatClient) async {
        isLoading = true
        profile = await chatClient.getProfile(userId: userId)
        isLoading = false

        if let p = profile {
            phone = p.phone ?? ""
            phoneVisible = p.phoneVisible
            location = p.location ?? ""
            locationVisible = p.locationVisible
        }

        // Load avatar
        let uid = userId ?? await chatClient.userId ?? ""
        if !uid.isEmpty {
            avatarData = await chatClient.getAvatar(userId: uid)
        }
    }

    func saveProfile(chatClient: ChatClient) async {
        isSaving = true
        errorMessage = nil

        let success = await chatClient.updateProfile(
            phone: phone.isEmpty ? nil : phone,
            phoneVisible: phoneVisible,
            location: location.isEmpty ? nil : location,
            locationVisible: locationVisible
        )

        isSaving = false

        if !success {
            errorMessage = "Failed to update profile"
        }
    }

    func uploadAvatar(imageData: Data, chatClient: ChatClient) async {
        isSaving = true
        let success = await chatClient.updateAvatar(imageData: imageData)
        isSaving = false

        if success {
            avatarData = imageData
        } else {
            errorMessage = "Failed to upload avatar"
        }
    }
}
