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 clientUserId = await chatClient.userId
        let uid = userId ?? clientUserId ?? ""
        if !uid.isEmpty {
            avatarData = await chatClient.getAvatar(userId: uid)
        }
    }

    @discardableResult
    func saveProfile(chatClient: ChatClient) async -> Bool {
        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"
        }
        return success
    }

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

        if success {
            // Reload avatar from server (it was resized/compressed)
            let clientUserId = await chatClient.userId ?? ""
            avatarData = await chatClient.getAvatar(userId: clientUserId)
        } else {
            errorMessage = msg.isEmpty ? "Failed to upload avatar" : msg
        }
    }

    // MARK: - Username Change

    func changeUsername(newUsername: String, chatClient: ChatClient) async -> Bool {
        isSaving = true
        errorMessage = nil
        let (success, msg) = await chatClient.changeUsername(newUsername: newUsername)
        isSaving = false
        if !success {
            errorMessage = msg
        }
        return success
    }

    // MARK: - Password Change

    func changePassword(oldPassword: String, newPassword: String, chatClient: ChatClient) async -> Bool {
        isSaving = true
        errorMessage = nil
        let (success, msg) = await chatClient.changePassword(oldPassword: oldPassword, newPassword: newPassword)
        isSaving = false
        if !success {
            errorMessage = msg
        }
        return success
    }
}
