//
//  VersionsLibraryView.swift
//  vibes
//
//  Landing screen for Versions exploration showing library and create button
//

import SwiftUI

// MARK: - Library Song Model
struct LibrarySong: Identifiable {
    let id = UUID()
    let title: String
    let albumArt: String
    let description: String
    var plays: Int = 0
    var likes: Int = 0
    var comments: Int = 0
}

struct VersionsLibraryView: View {
    // MARK: - Light Mode Color Overrides
    fileprivate struct LightColors {
        static let backgroundPrimary = Color(hex: "#fbf7f5")
        static let backgroundSecondary = Color(hex: "#f7f4ef")
        static let foregroundPrimary = Color(hex: "#101012")
        static let foregroundSecondary = Color(hex: "#7d7c84")
        static let foregroundTertiary = Color(hex: "#a3a3a3")
        static let borderPrimary = Color(hex: "#c2c2c1")
        static let accentOrange = Color(hex: "#ff8d28")
    }

    @Binding var selectedTab: NavTab
    @Binding var showCreateSheet: Bool
    @Binding var createdSongs: [LibrarySong]
    @State private var showNewSongAnimation: [UUID: Bool] = [:]
    @State private var shineOffset: [UUID: CGFloat] = [:]

    // Sample data for songs with album art
    private let sampleSongs: [(title: String, description: String, plays: Int, likes: Int, comments: Int, albumArt: String)] = [
        ("Rhythmic Dreams", "Electronic, energetic, +10", 6, 4, 1, "cry cried crying.png"),
        ("Whispering Winds", "Ambient, calm, +8", 3, 5, 2, "crystal healing.png"),
        ("Timeless Echoes", "Acoustic, soothing, +7", 2, 3, 8, "daylight.png"),
        ("Electric Nights", "Dance, pulsating, +9", 1, 7, 4, "ECLIPSE.png"),
        ("Serene Horizons", "Chill, laid-back, +6", 4, 6, 9, "feel good.png"),
        ("Fleeting Moments", "Alternative, melancholic, +5", 7, 2, 3, "fernery.png"),
        ("Midnight Chase", "Synthwave, retro, +12", 8, 9, 5, "flower in the wind.png"),
        ("Crystal Tears", "Emotional, piano, +8", 5, 4, 7, "Found.png"),
        ("Summer Breeze", "Pop, upbeat, +15", 12, 11, 3, "FREEEEEEEEE.png"),
        ("Neon Lights", "EDM, club, +20", 15, 14, 6, "gameboy colors.png"),
        ("Velvet Dreams", "Jazz, smooth, +7", 6, 8, 4, "going somewhere.png")
    ]

    var body: some View {
        ZStack {
            LightColors.backgroundPrimary
                .ignoresSafeArea()

            VStack(spacing: 0) {
                // Content - scrolls under header
                ScrollView {
                    VStack(alignment: .leading, spacing: 20) {
                        // Spacer for Library title and status bar
                        Color.clear
                            .frame(height: 40)

                        // Category cards
                        ScrollView(.horizontal, showsIndicators: false) {
                            HStack(spacing: 12) {
                                CategoryCard(title: "Drafts", backgroundColor: LightColors.backgroundSecondary, textColor: LightColors.foregroundPrimary, showBorder: true)
                                CategoryCard(title: "Shared", backgroundColor: LightColors.accentOrange, textColor: LightColors.backgroundPrimary)
                                CategoryCard(title: "Liked", backgroundColor: Color(hex: "#007bed"), textColor: LightColors.backgroundPrimary)
                                CategoryCard(title: "Playlists", backgroundColor: Color(hex: "#a10bba"), textColor: LightColors.backgroundPrimary)
                                CategoryCard(title: "Hooks", backgroundColor: Color(hex: "#d10028"), textColor: LightColors.backgroundPrimary)
                            }
                            .padding(.horizontal, 16)
                        }
                        .padding(.horizontal, -16) // Offset parent padding so cards can scroll edge to edge

                        // My Songs section
                        Text("My Songs")
                            .font(.system(size: 18, weight: .medium))
                            .foregroundColor(LightColors.foregroundPrimary)
                            .tracking(0.36)

                        // Songs list - created songs first, then sample songs
                        VStack(spacing: 12) {
                            // Created songs at the top
                            ForEach(createdSongs) { song in
                                SongRow(
                                    title: song.title,
                                    description: song.description,
                                    plays: song.plays,
                                    likes: song.likes,
                                    comments: song.comments,
                                    albumArt: song.albumArt,
                                    shineOffset: shineOffset[song.id] ?? -80
                                )
                                .opacity(showNewSongAnimation[song.id] ?? false ? 1 : 0)
                                .offset(y: showNewSongAnimation[song.id] ?? false ? 0 : -10)
                            }

                            // Sample songs below
                            ForEach(Array(sampleSongs.enumerated()), id: \.offset) { _, song in
                                SongRow(
                                    title: song.title,
                                    description: song.description,
                                    plays: song.plays,
                                    likes: song.likes,
                                    comments: song.comments,
                                    albumArt: song.albumArt,
                                    shineOffset: -80
                                )
                            }
                        }
                    }
                    .padding(.horizontal, 16)
                    .padding(.bottom, 102) // Space for bottom bar (86px nav + 16px safe area)
                }

                Spacer()
            }

            // Fixed Library header at top - matches background color
            VStack(spacing: 0) {
                // Library title
                HStack {
                    Text("Library")
                        .font(.system(size: 28, weight: .semibold))
                        .foregroundColor(LightColors.foregroundPrimary)
                        .tracking(0.56)
                        .padding(.horizontal, 16)
                        .padding(.bottom, 8)
                    Spacer()
                }
                .padding(.top, 8)
                .background(LightColors.backgroundPrimary.ignoresSafeArea(edges: .top))

                Spacer()
            }

            // Bottom Navigation Bar (Light mode with proper colors and height)
            VStack(spacing: 0) {
                Spacer()
                HStack(spacing: 0) {
                    // Hooks Tab (40% opacity)
                    NavTabButton(
                        tab: .hooks,
                        selectedTab: $selectedTab,
                        iconName: "Icon/playlist"
                    )
                    .opacity(0.4)
                    .colorMultiply(LightColors.foregroundPrimary)

                    // Explore Tab (40% opacity)
                    NavTabButton(
                        tab: .explore,
                        selectedTab: $selectedTab,
                        iconName: "Icon/explore"
                    )
                    .opacity(0.4)
                    .colorMultiply(LightColors.foregroundPrimary)

                    // Create Tab (Center - Special styling)
                    CreateTabButton(showCreateSheet: $showCreateSheet)

                    // Library Tab (100% opacity - active)
                    NavTabButton(
                        tab: .library,
                        selectedTab: $selectedTab,
                        iconName: "Icon/library"
                    )
                    .opacity(1.0)
                    .colorMultiply(LightColors.foregroundPrimary)

                    // Profile Tab (100% opacity)
                    NavTabButton(
                        tab: .profile,
                        selectedTab: $selectedTab,
                        profileImageName: "Avatar/8"
                    )
                    .opacity(1.0)
                }
                .frame(height: 56) // Nav content height
                .frame(maxWidth: .infinity)
                .background(
                    LightColors.backgroundPrimary
                        .overlay(
                            Rectangle()
                                .fill(LightColors.foregroundTertiary.opacity(0.2))
                                .frame(height: 0.5),
                            alignment: .top
                        )
                )
                .padding(.bottom, 0) // Let safe area handle bottom spacing
            }
        }
        .preferredColorScheme(.light)
        .navigationBarBackButtonHidden(true)
        .interactiveDismissDisabled()
        .onChange(of: createdSongs.count) { oldCount, newCount in
            // When a new song is added, trigger the animation
            if newCount > oldCount, let newSong = createdSongs.first {
                // Initially hide the song and position shine off-screen left
                showNewSongAnimation[newSong.id] = false
                shineOffset[newSong.id] = -80

                // Wait for existing songs to finish animating down (0.3s) + 0.2s pause, then animate new song in
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    withAnimation(.spring(response: 0.5, dampingFraction: 0.5)) {
                        showNewSongAnimation[newSong.id] = true
                    }

                    // Trigger shine effect after spring animation completes (~1.0s)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                        withAnimation(.linear(duration: 0.6)) {
                            shineOffset[newSong.id] = 80
                        }

                        // Reset shine position after animation completes
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
                            shineOffset[newSong.id] = -80
                        }
                    }
                }
            }
        }
    }
}

// MARK: - Category Card
private struct CategoryCard: View {
    let title: String
    let backgroundColor: Color
    let textColor: Color
    var showBorder: Bool = false

    var body: some View {
        ZStack(alignment: .bottomLeading) {
            RoundedRectangle(cornerRadius: 12)
                .fill(backgroundColor)
                .frame(width: 135, height: 102)
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(VersionsLibraryView.LightColors.borderPrimary, lineWidth: showBorder ? 1 : 0)
                )

            Text(title)
                .font(.system(size: 14, weight: .medium))
                .foregroundColor(textColor)
                .tracking(0.28)
                .padding(12)
        }
    }
}

// MARK: - Song Row
private struct SongRow: View {
    let title: String
    let description: String
    let plays: Int
    let likes: Int
    let comments: Int
    let albumArt: String
    let shineOffset: CGFloat

    var body: some View {
        HStack(spacing: 12) {
            // Album art from resources with shine effect
            ZStack {
                if let uiImage = UIImage(named: albumArt) {
                    Image(uiImage: uiImage)
                        .resizable()
                        .scaledToFill()
                        .frame(width: 52, height: 71)
                        .clipShape(RoundedRectangle(cornerRadius: 12))
                } else {
                    RoundedRectangle(cornerRadius: 12)
                        .fill(Color(hex: "#007bed"))
                        .frame(width: 52, height: 71)
                }

                // Shine overlay - always rendered but positioned off-screen when not animating
                LinearGradient(
                    gradient: Gradient(colors: [
                        .clear,
                        .white.opacity(1.0),
                        .clear
                    ]),
                    startPoint: .leading,
                    endPoint: .trailing
                )
                .frame(width: 120, height: 100)
                .rotationEffect(.degrees(-20))
                .offset(x: shineOffset)
                .clipShape(RoundedRectangle(cornerRadius: 12))
                .blendMode(.overlay)
            }
            .frame(width: 52, height: 71)
            .clipped()

            // Song info
            VStack(alignment: .leading, spacing: 5) {
                Text(title)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(VersionsLibraryView.LightColors.foregroundPrimary)
                    .tracking(0.28)

                Text(description)
                    .font(.system(size: 14, weight: .regular))
                    .foregroundColor(VersionsLibraryView.LightColors.foregroundSecondary)
                    .tracking(0.28)

                // Stats row
                HStack(spacing: 8) {
                    StatItem(iconName: "play.fill", count: plays)
                    StatItem(iconName: "hand.thumbsup.fill", count: likes)
                    StatItem(iconName: "bubble.left.fill", count: comments)
                }
            }

            Spacer()
        }
    }
}

// MARK: - Stat Item
private struct StatItem: View {
    let iconName: String
    let count: Int

    var body: some View {
        HStack(spacing: 2) {
            Image(systemName: iconName)
                .font(.system(size: 10, weight: .regular))
                .foregroundColor(VersionsLibraryView.LightColors.foregroundSecondary)

            Text("\(count)")
                .font(.system(size: 12, weight: .regular))
                .foregroundColor(VersionsLibraryView.LightColors.foregroundSecondary)
                .tracking(0.24)
        }
    }
}

#Preview {
    VersionsLibraryView(selectedTab: .constant(.library), showCreateSheet: .constant(false), createdSongs: .constant([]))
}
