import SwiftUI
import NukeUI

struct SongCard: View {
    @Environment(AudioManager.self) var audioManager

    let song: UploadedSong
    let onMoreTap: () -> Void
    let onRemixTap: () -> Void
    let onCardTap: () -> Void
    
    @State private var barHeights: [CGFloat] = [4, 4, 4]
    @State private var animationTimer: Timer?

    private var isPlaying: Bool {
        audioManager.currentlyPlayingSong?.id == song.id && audioManager.isCurrentlyPlaying
    }

    private var isCurrentSong: Bool {
        audioManager.currentlyPlayingSong?.id == song.id
    }

    init(
        song: UploadedSong,
        onMoreTap: @escaping () -> Void = {},
        onRemixTap: @escaping () -> Void = {},
        onCardTap: @escaping () -> Void = {}
    ) {
        self.song = song
        self.onMoreTap = onMoreTap
        self.onRemixTap = onRemixTap
        self.onCardTap = onCardTap
    }

    var body: some View {
        VStack(spacing: 12) {
            // Album artwork with more button
            ZStack {
                LazyImage(url: song.imageURL == nil ? nil : URL(string: song.imageURL!)) { state in
                    if let image = state.image {
                        image.resizable()
                            .aspectRatio(1.0, contentMode: .fill)
                    } else {
                        Rectangle()
                            .aspectRatio(1, contentMode: .fit)
                            .foregroundStyle(Constants.Colors.Background.secondary)
                    }
                }
                .cornerRadius(16)
                
                // 50% black overlay when playing
                if isCurrentSong {
                    RoundedRectangle(cornerRadius: 16)
                        .fill(Color.black.opacity(0.5))
                }
                
                // Centered sound waves when playing
                if isCurrentSong {
                    HStack(spacing: 2) {
                        ForEach(0..<3, id: \.self) { index in
                            Capsule()
                                .fill(.white)
                                .frame(width: 3)
                                .frame(height: barHeights[index])
                                .animation(.easeOut(duration: 0.15), value: barHeights[index])
                        }
                    }
                    .onAppear {
                        if isPlaying {
                            startAudioVisualization()
                        }
                    }
                    .onChange(of: isPlaying) { _, newValue in
                        if newValue {
                            startAudioVisualization()
                        } else {
                            stopAudioVisualization()
                        }
                    }
                    .onDisappear {
                        stopAudioVisualization()
                    }
                }

                VStack {
                    HStack {
                        Spacer()
                        Button(action: onMoreTap) {
                            Image(systemName: "ellipsis")
                                .frame(width: 16, height: 16)
                                .foregroundColor(.white)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    .padding(16)
                    Spacer()
                }
            }

            // Song info and remix button
            VStack(spacing: 8) {
                VStack(spacing: 4) {
                    HStack {
                        Text(song.name)
                            .font(Constants.Typography.smallTitle)
                            .foregroundColor(
                                isCurrentSong 
                                ? Constants.Colors.Accent.brand 
                                : Color(hex: "#f7f4ef")
                            )
                            .lineLimit(1)
                            .truncationMode(.tail)
                            .tracking(0.24)
                        Spacer()
                    }

                    HStack {
                        Text(song.artistName)
                            .font(Constants.Typography.small)
                            .foregroundColor(Color(hex: "#a3a3a3"))
                            .lineLimit(1)
                            .tracking(0.24)
                        Spacer()
                    }
                }

                Button(action: onRemixTap) {
                    HStack(spacing: 4) {
                        Image("Icon/remix")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 16, height: 16)
                            .foregroundColor(Color(hex: "#f7f4ef"))

                        Text("Remix")
                            .font(Constants.Typography.xSmallTitle)
                            .foregroundColor(Color(hex: "#f7f4ef"))
                            .tracking(0.28)
                    }
                    .frame(maxWidth: .infinity)
                    .frame(height: 32)
                    .background(
                        RoundedRectangle(cornerRadius: 100)
                            .fill(Color.white.opacity(0.04))
                    )
                }
                .buttonStyle(PlainButtonStyle())
            }
            .padding(.horizontal, 8)
            .padding(.bottom, 16)
        }
        .padding(.top, 8)
        .padding(.horizontal, 8)
        .background(
            RoundedRectangle(cornerRadius: 24)
                .fill(Color.white.opacity(0.04))
        )
        .onTapGesture {
            onCardTap()
        }
    }
    
    private func startAudioVisualization() {
        // Start with flat state
        barHeights = [4, 4, 4]
        
        // Create random, lifelike audio visualization
        animationTimer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
            withAnimation(.easeOut(duration: 0.2)) {
                // Generate semi-random heights that feel like audio levels
                barHeights[0] = randomAudioHeight(baseHeight: 8, variation: 4)
                barHeights[1] = randomAudioHeight(baseHeight: 12, variation: 6) // Middle bar tends to be tallest
                barHeights[2] = randomAudioHeight(baseHeight: 10, variation: 4)
            }
            
            // Sometimes create a subtle "beat" effect where all bars spike slightly
            if Int.random(in: 1...40) == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    withAnimation(.easeOut(duration: 0.15)) {
                        barHeights = [14, 18, 12]
                    }
                }
            }
        }
    }
    
    private func stopAudioVisualization() {
        animationTimer?.invalidate()
        animationTimer = nil
        
        // Animate to flat state
        withAnimation(.easeOut(duration: 0.3)) {
            barHeights = [4, 4, 4]
        }
    }
    
    private func randomAudioHeight(baseHeight: CGFloat, variation: CGFloat) -> CGFloat {
        let randomVariation = CGFloat.random(in: -variation...variation)
        return max(4, baseHeight + randomVariation) // Minimum height of 4
    }
}

#Preview {
    SongCard(
        song: UploadedSong(
            id: "2",
            name: "Another Great Song",
            artistName: "The Weeknd",
            artistId: "artist2",
            createdAt: .now,
            imageURL: nil,
            audioURL: nil,
            originalPrompt: "dark moody R&B track",
            rewrittenPrompt: "R&B, dark, moody, soulful vocals, catchy chorus"
        ),
        onMoreTap: { print("More tapped") },
        onRemixTap: { print("Remix tapped") },
        onCardTap: { print("Card tapped") }
    )
}
