import SwiftUI
import NukeUI

struct ExploreTabView: View {
    @State private var selectedSong: UploadedSong?

    @EnvironmentObject var artistManager: ArtistManager
    @EnvironmentObject var uploadedSongManager: UploadedSongManager
    @EnvironmentObject var tweaksManager: TweaksManager

    @State private var selectedGenre = "Trending"
    @Binding var navigationPath: NavigationPath
    private let genres = ["Trending", "Pop", "Rock", "Hip Hop", "Jazz", "Electronic", "Country", "R&B", "Classical", "Indie"]

    @Environment(AudioManager.self) private var audioManager
    
    @State private var showTweaksSheet = false

    init(navigationPath: Binding<NavigationPath> = .constant(NavigationPath())) {
        self._navigationPath = navigationPath
    }
    
    // Sample song data with genres
    private var allSongs: [(title: String, artist: String, genre: String)] {
        [
            ("Yellow", "Coldplay", "Rock"),
            ("Blinding Lights", "The Weeknd", "Pop"),
            ("God's Plan", "Drake", "Hip Hop"),
            ("Take Five", "Dave Brubeck", "Jazz"),
            ("One More Time", "Daft Punk", "Electronic"),
            ("Friends in Low Places", "Garth Brooks", "Country"),
            ("Crazy in Love", "Beyoncé", "R&B"),
            ("Claire de Lune", "Claude Debussy", "Classical"),
            ("Ho Hey", "The Lumineers", "Indie"),
            ("Shape of You", "Ed Sheeran", "Pop"),
            ("Bohemian Rhapsody", "Queen", "Rock"),
            ("HUMBLE.", "Kendrick Lamar", "Hip Hop"),
            ("Blue in Green", "Miles Davis", "Jazz"),
            ("Strobe", "Deadmau5", "Electronic"),
            ("The Dance", "Garth Brooks", "Country"),
            ("Single Ladies", "Beyoncé", "R&B"),
            ("Moonlight Sonata", "Beethoven", "Classical"),
            ("Electric Feel", "MGMT", "Indie")
        ]
    }

    var body: some View {
        NavigationStack(path: $navigationPath) {
            ScrollView {
                VStack(spacing: 0) {
                    artistsSection
                    genreFilterSection
                    songsGridSection
                }
            }
            .background(Constants.Colors.Background.primary)
            .navigationTitle("Explore")
            .toolbarTitleDisplayMode(.inlineLarge)
            .toolbar {
                ToolbarItem {
                    Button {
                        showTweaksSheet = true
                    } label: {
                        Image("Icon/notifications")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 24, height: 24)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                    }
                }
                ToolbarSpacer()
                ToolbarItem {
                    NavigationLink(destination: TrendingView()) {
                        Image("Icon/search")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 24, height: 24)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                    }
                }
            }
        }
        .id("ExploreNavigationStack")
        .preferredColorScheme(.dark)
        .sheet(item: $selectedSong) { item in
            RemixSelectionView(song: item)
        }
        .sheet(isPresented: $showTweaksSheet) {
            TweaksSheet(tweaksManager: tweaksManager)
                .presentationDetents([.large])
        }
    }

    private var artistsSection: some View {
        VStack(spacing: 12) {
            HStack {
                Text("Artists")
                    .font(Constants.Typography.mediumTitle)
                    .foregroundColor(Constants.Colors.Foreground.primary)
                
                Spacer()
                
                NavigationLink(destination: ArtistsView()) {
                    Text("See More")
                        .font(Constants.Typography.smallTitle)
                        .foregroundColor(Constants.Colors.Foreground.secondary)
                }
            }
            .padding(.horizontal, 16)
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 16) {
                    ForEach(artistManager.artists) { artist in
                        NavigationLink(destination: ArtistProfileView(artist: artist)) {
                            artistCircle(artist: artist)
                        }
                    }
                }
                .padding(.horizontal, 16)
            }
        }
        .padding(.vertical, 16)
    }
    
    private func artistCircle(artist: Artist) -> some View {
        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.smallTitle)
                .foregroundColor(Constants.Colors.Foreground.primary)
                .multilineTextAlignment(.center)
                .lineLimit(1)
        }
        .frame(width: 100)
    }
    
    private var genreFilterSection: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 4) {
                ForEach(genres, id: \.self) { genre in
                    Button(action: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            selectedGenre = genre
                        }
                    }) {
                        Text(genre)
                            .font(Constants.Typography.mediumTitle)
                            .foregroundColor(selectedGenre == genre ?
                                Constants.Colors.Foreground.primary :
                                Constants.Colors.Foreground.secondary)
                            .padding(.horizontal, 16)
                            .padding(.vertical, 8)
                            .background(
                                RoundedRectangle(cornerRadius: 20)
                                    .fill(selectedGenre == genre ?
                                        Constants.Colors.Background.Fog.thin :
                                        Color.clear)
                            )
                    }
                    .buttonStyle(PlainButtonStyle())
                }
            }
            .padding(.horizontal, 16)
        }
        .padding(.vertical, 12)
    }
    
    private var songsGridSection: some View {
        let filteredSongs = tweaksManager.isFocusModeEnabled
        ? uploadedSongManager.songs.filter { $0.hasBeenRemixed }.sorted(by: { s1, s2 in s1.name < s2.name})
            : uploadedSongManager.songs.sorted(by: { s1, s2 in s1.name < s2.name})

        return LazyVGrid(columns: [
            GridItem(.flexible(), spacing: 16),
            GridItem(.flexible(), spacing: 16)
        ], spacing: 16) {
            ForEach(filteredSongs) { song in
                SongCard(song: song) {
                    
                } onRemixTap: {
                    selectedSong = song
                } onCardTap: {
                    // Play from filtered songs playlist
                    if let songIndex = filteredSongs.firstIndex(where: { $0.id == song.id }) {
                        audioManager.playPlaylist(filteredSongs, startingAt: songIndex)
                    } else {
                        // Fallback to single song if not found in playlist
                        audioManager.playPlaylist([song], startingAt: 0)
                    }
                }
            }
        }
        .padding(.horizontal, 16)
        .padding(.top, 8)
        .animation(.easeInOut(duration: 0.3), value: selectedGenre)
    }
}

#Preview {
    NavigationStack {
        ExploreTabView ()
    }
}
