import SwiftUI

struct InlineChatPlayer: View {
    let songTitle: String
    let genres: [String]
    let isPlaying: Bool
    let isSelected: Bool
    let progress: Double // 0.0 to 1.0
    let artworkGradient: LinearGradient?
    let onPlayPause: () -> Void
    let onSelect: () -> Void
    let onExpand: () -> Void
    let onProgressChanged: (Double) -> Void
    let onScrubStart: (() -> Void)?
    let onScrubEnd: (() -> Void)?
    let onThumbsUp: () -> Void
    let onThumbsDown: () -> Void
    let onShare: () -> Void
    let onMore: () -> Void
    
    var body: some View {
        VStack(spacing: 16) {
            // Album Artwork Section (Play/Pause tap area)
            Button(action: {
                // If song is not currently playing AND not selected, select it when starting playback
                if !isPlaying && !isSelected {
                    onSelect()
                }
                onPlayPause()
            }) {
                ZStack {
                    // Thermal Shader Artwork
                    ArtworkShader(gradient: artworkGradient, isAlive: isPlaying)
                        .aspectRatio(1, contentMode: .fit)
                        .frame(maxWidth: 343)
                        .cornerRadius(24)
                    
                    // Interactive waveform with pink progress line
                    let shouldShowWaveform = isPlaying || progress > 0.01 // ~1-2 seconds for typical song lengths
                    if shouldShowWaveform {
                        VStack {
                            Spacer()
                            
                            HStack {
                                Spacer()
                                
                                // Waveform with scrubbing
                                WaveformScrubber(
                                    progress: progress,
                                    onProgressChanged: { newProgress in
                                        onProgressChanged(newProgress)
                                    },
                                    onScrubStart: {
                                        onScrubStart?()
                                    },
                                    onScrubEnd: {
                                        onScrubEnd?()
                                    }
                                )
                                .frame(width: 128, height: 24)
                                
                                Spacer()
                            }
                            .padding(.bottom, 16)
                        }
                    }
                    
                    // Play Button or Pause Button Overlay
                    if isPlaying {
                        // Pause Button
                        Image("Icon/pause")
                            .resizable()
                            .frame(width: 32, height: 32)
                            .foregroundColor(.white)
                    } else {
                        Image("Icon/play")
                            .resizable()
                            .frame(width: 32, height: 32)
                            .foregroundColor(.white)
                    }
                    
                    // Expand Button (Top Right Corner)
                    VStack {
                        HStack {
                            Spacer()
                            Button(action: onExpand) {
                                    Image("Icon/expand-content")
                                        .resizable()
                                        .frame(width: 16, height: 16)
                                        .foregroundColor(.white)

                            }
                            .padding(.trailing, 12)
                            .padding(.top, 12)
                        }
                        Spacer()
                    }
                }
            }
            .buttonStyle(PlainButtonStyle())
            
            // Song Info and Actions Section (Selection tap area)
            Button(action: onSelect) {
                VStack(spacing: 8){
                    // Song Info Section
                    VStack(spacing: 0) {
                        HStack {
                            Text(songTitle)
                                .font(Constants.Typography.smallTitle)
                                .kerning(0.24)
                                .foregroundColor(isSelected ? Constants.Colors.Accent.brand : Constants.ForegroundPrimary)
                            Spacer()
                        }
                        
                        HStack {
                            Text(genres.joined(separator: ", "))
                                .font(Constants.Typography.small)
                                .kerning(0.24)
                                .foregroundColor(.white.opacity(0.7))
                                .lineLimit(2)
                                .multilineTextAlignment(.leading)
                            Spacer()
                        }
                    }
                    
                    // Action Buttons
                    HStack(spacing: 16) {
                        // Thumbs Up
                        Button(action: onThumbsUp) {
                            Image("Icon/thumbs-up")
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(Constants.Colors.Background.Fog.dense)
                        }
                        
                        // Thumbs Down
                        Button(action: onThumbsDown) {
                            Image("Icon/thumbs-down")
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(Constants.Colors.Background.Fog.dense)
                        }
                        
                        // Share
                        Button(action: onShare) {
                            Image("Icon/share-arrow")
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(Constants.Colors.Background.Fog.dense)
                        }
                        
                        // More
                        Button(action: onMore) {
                            Image("Icon/more-horizontal")
                                .resizable()
                                .renderingMode(.template)
                                .frame(width: 16, height: 16)
                                .foregroundColor(Constants.Colors.Background.Fog.dense)
                        }
                        
                        Spacer()
                    }
                }
                .padding(.horizontal, 8)
            }
            .buttonStyle(PlainButtonStyle())
        }
        .padding(.horizontal, 8)
        .padding(.top, 8)
        .padding(.bottom, 16)
        .frame(minWidth: 175)
        .fixedSize(horizontal: false, vertical: true)
        .background(
            RoundedRectangle(cornerRadius: 24)
                .fill(isSelected ? Constants.Colors.Background.Fog.thin : Color.clear)
        )
    }
}

struct AudioBar: View {
    let baseHeight: CGFloat
    let isAnimating: Bool
    @State private var animationHeight: CGFloat = 6
    @State private var animationTimer: Timer?
    
    var body: some View {
        RoundedRectangle(cornerRadius: 100)
            .fill(Color.white)
            .frame(width: 3, height: animationHeight)
            .onAppear {
                startAnimation()
            }
            .onChange(of: isAnimating) { _, newValue in
                if newValue {
                    startAnimation()
                } else {
                    stopAnimation()
                }
            }
    }
    
    private func startAnimation() {
        guard isAnimating else { return }
        animateToRandomHeight()
    }
    
    private func stopAnimation() {
        animationTimer?.invalidate()
        animationTimer = nil
        withAnimation(.easeInOut(duration: 0.3)) {
            animationHeight = 6
        }
    }
    
    private func animateToRandomHeight() {
        guard isAnimating else { return }
        
        let randomHeight = CGFloat.random(in: 6...max(6, baseHeight))
        let duration = Double.random(in: 0.3...0.8)
        
        withAnimation(.easeInOut(duration: duration)) {
            animationHeight = randomHeight
        }
        
        animationTimer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { _ in
            animateToRandomHeight()
        }
    }
}

#Preview {
    HStack(spacing: 16) {
        InlineChatPlayer(
            songTitle: "Summertime #1",
            genres: ["hip-hop", "rnb", "indie"],
            isPlaying: false,
            isSelected: true,
            progress: 0.0,
            artworkGradient: LinearGradient(colors: [Color.orange, Color.red], startPoint: .topLeading, endPoint: .bottomTrailing),
            onPlayPause: { print("Play/Pause tapped") },
            onSelect: { print("Select tapped") },
            onExpand: { print("Expand tapped") },
            onProgressChanged: { progress in print("Progress changed: \(progress)") },
            onScrubStart: { print("Scrub started") },
            onScrubEnd: { print("Scrub ended") },
            onThumbsUp: { print("Thumbs up tapped") },
            onThumbsDown: { print("Thumbs down tapped") },
            onShare: { print("Share tapped") },
            onMore: { print("More tapped") }
        )
        
        InlineChatPlayer(
            songTitle: "Ocean Waves",
            genres: ["ambient", "chill"],
            isPlaying: true,
            isSelected: false,
            progress: 0.67,
            artworkGradient: LinearGradient(colors: [Color.blue, Color.cyan], startPoint: .topLeading, endPoint: .bottomTrailing),
            onPlayPause: { print("Play/Pause tapped") },
            onSelect: { print("Select tapped") },
            onExpand: { print("Expand tapped") },
            onProgressChanged: { progress in print("Progress changed: \(progress)") },
            onScrubStart: { print("Scrub started") },
            onScrubEnd: { print("Scrub ended") },
            onThumbsUp: { print("Thumbs up tapped") },
            onThumbsDown: { print("Thumbs down tapped") },
            onShare: { print("Share tapped") },
            onMore: { print("More tapped") }
        )
    }
    .padding()
    .background(Constants.Colors.Background.primary)
}

struct WaveformScrubber: View {
    let progress: Double
    let onProgressChanged: (Double) -> Void
    let onScrubStart: () -> Void
    let onScrubEnd: () -> Void
    
    @State private var isScrubbing: Bool = false
    
    // Static waveform data - different heights between 4 and 24
    private let waveformHeights: [CGFloat] = [
        4, 8, 19, 15, 8, 19, 23, 6, 15, 21, 7, 16, 23, 23, 16, 8, 11, 12, 20, 7, 23, 15, 9, 21, 22, 21, 13, 15, 20, 9, 12, 20, 22, 22, 16, 6, 6, 11, 14, 19, 16, 20, 4
    ]
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // Waveform bars
                HStack(spacing: 2) {
                    ForEach(0..<waveformHeights.count, id: \.self) { index in
                        let barProgress = Double(index) / Double(waveformHeights.count - 1)
                        let isPlayed = barProgress <= progress
                        
                        RoundedRectangle(cornerRadius: 0.5)
                            .fill(isPlayed ? Color.white : Color.white.opacity(0.3))
                            .frame(width: 1, height: waveformHeights[index])
                    }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
                
                // Pink progress line
                RoundedRectangle(cornerRadius: 1)
                    .fill(Constants.Colors.Accent.brand)
                    .frame(width: 2, height: 24)
                    .position(
                        x: geometry.size.width * CGFloat(progress),
                        y: geometry.size.height / 2
                    )
                    .allowsHitTesting(false)
                
                // Invisible drag area for scrubbing
                Rectangle()
                    .fill(Color.clear)
                    .contentShape(Rectangle())
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .onChanged { value in
                                // Only call onScrubStart once at the beginning of the drag
                                if !isScrubbing {
                                    isScrubbing = true
                                    onScrubStart()
                                }
                                let newProgress = max(0, min(1, value.location.x / geometry.size.width))
                                onProgressChanged(newProgress)
                            }
                            .onEnded { _ in
                                isScrubbing = false
                                onScrubEnd()
                            }
                    )
            }
        }
    }
}

#Preview("WaveformScrubber") {
    VStack(spacing: 20) {
        WaveformScrubber(
            progress: 0.3,
            onProgressChanged: { progress in
                print("Progress: \(progress)")
            },
            onScrubStart: {
                print("Scrub started")
            },
            onScrubEnd: {
                print("Scrub ended")
            }
        )
        .frame(width: 128, height: 24)
        .background(Color.black.opacity(0.2))
        
        WaveformScrubber(
            progress: 0.7,
            onProgressChanged: { progress in
                print("Progress: \(progress)")
            },
            onScrubStart: {
                print("Scrub started")
            },
            onScrubEnd: {
                print("Scrub ended")
            }
        )
        .frame(width: 128, height: 24)
        .background(Color.black.opacity(0.2))
    }
    .padding()
    .background(Constants.Colors.Background.primary)
}
