import SwiftUI

struct UserAvatarView: View {
    @EnvironmentObject private var userService: UserService
    @State private var showImagePicker: Bool = false
    @State private var selectedImage: UIImage?
    @State private var isUploading: Bool = false
    
    private var authResponse: AuthResponse? {
        if case .signedIn(let authResponse) = userService.signedInState {
            return authResponse
        }
        return nil
    }
    
    var userImageURL: URL? {
        return authResponse?.avatar
    }
    
    var body: some View {
        ZStack {
            ProgressView()
                .progressViewStyle(.circular)
                .opacity(isUploading ? 1 : 0)
            
            AvatarView(url: userImageURL)
                .sheet(isPresented: $showImagePicker) {
                    ImagePicker(selectedImage: $selectedImage)
                        .accentColor(ColorName.tint.color)
                }
                .onTapGesture {
                    if authResponse != nil {
                        showImagePicker = true
                    }
                }
                .onChange(of: selectedImage) { selectedImage in
                    if let image = selectedImage {
                        uploadImage(image)
                    }
                }
                .opacity(isUploading ? 0.3 : 1)
        }
        .transition(.opacity)
        .animation(.easeInOut, value: isUploading)
    }
    
    private func uploadImage(_ image: UIImage) {
        Task {
            isUploading = true
            do {
                try await userService.updateAvatar(image)
                await userService.signInWithStoredToken()
                isUploading = false
            } catch {
                // TODO: Handle error
                print(error)
                isUploading = false
            }
        }
    }
}
