import SwiftUI
import NukeUI

struct ArtistsView: View {
    @EnvironmentObject private var artistManager: ArtistManager
    
    var body: some View {
        ScrollView {
            LazyVGrid(columns: [
                GridItem(.flexible(), spacing: 16),
                GridItem(.flexible(), spacing: 16),
                GridItem(.flexible(), spacing: 16)
            ], spacing: 24) {
                ForEach(artistManager.artists) { artist in
                    artistCircle(artist: artist)
                }
            }
            .padding(.horizontal, 16)
            .padding(.top, 8)
        }
        .background(Constants.Colors.Background.primary)
        .navigationTitle("Artists")
        .navigationBarTitleDisplayMode(.inline)
        .preferredColorScheme(.dark)
        .onAppear {
            artistManager.fetchArtists()
        }
        .onDisappear {
            artistManager.stopListening()
        }
    }
    
    private func artistCircle(artist: Artist) -> some View {
        NavigationLink {
            ArtistProfileView(artist: artist)
        } label: {
            VStack(spacing: 8) {
                LazyImage(url: artist.avatarURL == nil ? nil : URL(string: artist.avatarURL!)) { state in
                    if let image = state.image {
                        image.resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 100, height: 100)
                    } else {
                        Circle()
                            .foregroundStyle(Constants.Colors.Background.secondary)
                    }
                }
                .clipShape(Circle())
                .frame(width: 100, height: 100)
                
                Text(artist.displayName)
                    .font(Constants.Typography.xSmallTitle)
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .multilineTextAlignment(.center)
                    .lineLimit(1)
            }
            .frame(width: 100)
        }
    }
}

#Preview {
    NavigationStack {
        ArtistsView()
    }
}
