import SwiftUI

struct LibraryTabView: View {
    @State private var selectedSong: UploadedSong?
    @State private var selectedSegment = 0 // 0 = All songs, 1 = Liked
    
    @StateObject private var songManager = LibrarySongManager.shared
    
    @Environment(AudioManager.self) private var audioManager

    // Support for dummy data in previews
    let previewSongs: [UploadedSong]?
    
    init(previewSongs: [UploadedSong]? = nil) {
        self.previewSongs = previewSongs
    }
    
    private var songsToDisplay: [UploadedSong] {
        if let previewSongs = previewSongs {
            return previewSongs
        } else {
            // Combine loading songs at the top with regular songs
            return songManager.songs
        }
    }
    
    private var isLoadingState: Bool {
        previewSongs != nil ? false : songManager.isLoading
    }
    
    private var errorMessage: String? {
        previewSongs != nil ? nil : songManager.errorMessage
    }
    
    private var filteredSongs: [UploadedSong] {
        switch selectedSegment {
        case 0: // All songs
            return songsToDisplay
        case 1: // Liked songs
            return songsToDisplay.filter { $0.isLikedByCreator ?? false }
        default:
            return songsToDisplay
        }
    }

    var body: some View {
        NavigationStack {
            ScrollView {
                LazyVStack(spacing: 0) {
                    // Segmented Control
                    Picker("Library Section", selection: $selectedSegment) {
                        Text("All songs").tag(0)
                        Text("Liked").tag(1)
                    }
                    .pickerStyle(SegmentedPickerStyle())
                    .font(.subheadline)
                    .padding(.horizontal, 16)
                    .padding(.vertical, 12)

                    // Songs List
                    if isLoadingState && songsToDisplay.isEmpty {
                        VStack(spacing: 12) {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle(tint: Constants.Colors.Foreground.primary))
                            Text("Loading songs...")
                                .font(Constants.Typography.small)
                                .foregroundColor(Constants.Colors.Foreground.tertiary)
                        }
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                    } else if let errorMessage = errorMessage {
                        VStack(spacing: 12) {
                            Image(systemName: "exclamationmark.triangle")
                                .font(.system(size: 40))
                                .foregroundColor(Constants.Colors.Foreground.tertiary)
                            Text(errorMessage)
                                .font(Constants.Typography.mediumRegular)
                                .foregroundColor(Constants.Colors.Foreground.tertiary)
                                .multilineTextAlignment(.center)
                        }
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .padding(.horizontal, 24)
                    } else if songsToDisplay.isEmpty {
                        VStack(spacing: 12) {
                            Image(systemName: "music.note.list")
                                .font(.system(size: 40))
                                .foregroundColor(Constants.Colors.Foreground.tertiary)
                            Text("No songs yet")
                                .font(Constants.Typography.mediumRegular)
                                .foregroundColor(Constants.Colors.Foreground.tertiary)
                            Text("Create your first song to see it here")
                                .font(Constants.Typography.small)
                                .foregroundColor(Constants.Colors.Foreground.tertiary)
                                .multilineTextAlignment(.center)
                        }
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .padding(.horizontal, 24)
                    } else {
                        ForEach(filteredSongs) { song in
                            LibrarySongRow(song: song, playlist: filteredSongs, showRemixIcon: true) { song in
                                selectedSong = song
                            }
                        }
                    }
                }
            }
            .background(Constants.Colors.Background.primary)
            .navigationTitle("Library")
            .toolbarTitleDisplayMode(.inlineLarge)
            .toolbar {
                ToolbarItem {
                    Button {
                        print("Notifications tapped")
                    } 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("LibraryNavigationStack")
        .preferredColorScheme(.dark)
        .onAppear {
            // Only fetch songs if not using preview data
            if previewSongs == nil {
                songManager.fetchUserCreatedSongs()
            }
        }
        .onDisappear {
            // Keep listening for updates, don't stop
        }
        .sheet(item: $selectedSong) { item in
            RemixSelectionView(song: item)
        }
    }
}

#Preview {
    let dummySongs = [
        UploadedSong(
            id: "1",
            name: "Midnight Dreams",
            artistName: "Luna",
            artistId: "artist1",
            createdAt: .now,
            imageURL: nil,
            audioURL: "https://example.com/song1.mp3",
            originalPrompt: "A dreamy synthwave track about midnight adventures",
            rewrittenPrompt: nil
        ),
        UploadedSong(
            id: "2", 
            name: "Electric Sunset",
            artistName: "Neon Waves",
            artistId: "artist2",
            createdAt: .now,
            imageURL: nil,
            audioURL: "https://example.com/song2.mp3",
            originalPrompt: "Upbeat electronic music with sunset vibes",
            rewrittenPrompt: nil
        ),
        UploadedSong(
            id: "3",
            name: "Coffee Shop Jazz",
            artistName: "The Smooth Collective",
            artistId: "artist3",
            createdAt: .now,
            imageURL: nil,
            audioURL: "https://example.com/song3.mp3",
            originalPrompt: "Relaxing jazz perfect for a cozy coffee shop",
            rewrittenPrompt: nil
        ),
        UploadedSong(
            id: "4",
            name: "Ocean Breeze",
            artistName: "Coastal Sounds",
            artistId: "artist4",
            createdAt: .now,
            imageURL: nil,
            audioURL: "https://example.com/song4.mp3",
            originalPrompt: "Ambient music inspired by ocean waves",
            rewrittenPrompt: nil
        ),
        UploadedSong(
            id: "5",
            name: "Mountain High",
            artistName: "Peak Performers",
            artistId: "artist5",
            createdAt: .now,
            imageURL: nil,
            audioURL: "https://example.com/song5.mp3",
            originalPrompt: "Epic orchestral piece inspired by mountain peaks",
            rewrittenPrompt: nil
        )
    ]
    
    NavigationStack {
        LibraryTabView(previewSongs: dummySongs)
    }
}
