import SwiftUI

struct CreateAudioPlayer: View {
    let songTitle: String
    let artworkGradient: LinearGradient
    let isPlaying: Bool
    let onPlayPause: () -> Void

    @State private var isDragging: Bool = false
    @State private var playbackProgress = AudioManager.shared.progress
    private let audioManager = AudioManager.shared

    private var currentTime: String {
        let seconds = playbackProgress.currentProgress * playbackProgress.totalDuration
        return formatTime(seconds)
    }

    private var totalTime: String {
        formatTime(playbackProgress.totalDuration)
    }

    init(
        songTitle: String = "Magical Vibes",
        artworkGradient: LinearGradient? = nil,
        isPlaying: Bool = false,
        onPlayPause: @escaping () -> Void = {}
    ) {
        self.songTitle = songTitle
        self.artworkGradient = artworkGradient ?? Self.defaultGradient
        self.isPlaying = isPlaying
        self.onPlayPause = onPlayPause
    }
    
    var body: some View {
        VStack(spacing: 16) {
            // Header with play button and title
            HStack(spacing: 16) {
                Button(action: onPlayPause) {
                    ZStack {
                        ArtworkShader(gradient: artworkGradient, isAlive: true)
                            .frame(width: 40, height: 40)
                            .cornerRadius(12)
                        
                        if isPlaying {
                            Image("Icon/pause")
                                .resizable()
                                .frame(width: 16, height: 16)
                                .foregroundColor(Constants.Colors.Foreground.primary)
                        } else {
                            Image("Icon/play")
                                .resizable()
                                .frame(width: 16, height: 16)
                                .foregroundColor(Constants.Colors.Foreground.primary)
                        }
                    }
                }
                .buttonStyle(PlainButtonStyle())
                
                Text(songTitle)
                    .font(Constants.Typography.small)
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .lineLimit(1)
                
                Spacer()
            }
            
            // Scrubber component
            VStack(spacing: 12) {
                // Progress bar
                GeometryReader { geometry in
                    ZStack(alignment: .leading) {
                        // Background track
                        RoundedRectangle(cornerRadius: 25)
                            .fill(Color.white.opacity(0.2))
                            .frame(height: 4)
                        
                        // Progress track
                        RoundedRectangle(cornerRadius: 25)
                            .fill(Constants.Colors.Accent.brand)
                            .frame(width: geometry.size.width * CGFloat(playbackProgress.currentProgress), height: 4)

                        // Scrubber handle
                        Circle()
                            .fill(Color.white)
                            .frame(width: 10, height: 10)
                            .shadow(color: .black.opacity(0.25), radius: 1, x: 0, y: 0)
                            .offset(x: geometry.size.width * CGFloat(playbackProgress.currentProgress) - 5)
                    }
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .onChanged { value in
                                if !isDragging {
                                    isDragging = true
                                    audioManager.startScrubbing()
                                }

                                let progress = max(0, min(1, value.location.x / geometry.size.width))
                                audioManager.seekToProgress(progress)
                            }
                            .onEnded { _ in
                                isDragging = false
                                audioManager.endScrubbing()
                            }
                    )
                }
                .frame(height: 10)
                
                // Time labels
                HStack {
                    Text(currentTime)
                        .font(Constants.Typography.timecode.weight(.medium))
                        .foregroundColor(.white.opacity(0.5))
                        .shadow(color: .black.opacity(0.35), radius: 2, x: 0, y: 0)
                    
                    Spacer()
                    
                    Text(totalTime)
                        .font(Constants.Typography.timecode.weight(.medium))
                        .foregroundColor(.white.opacity(0.5))
                        .shadow(color: .black.opacity(0.35), radius: 2, x: 0, y: 0)
                }
            }
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Constants.Colors.Background.Fog.thin)
        )
    }
    
    private func formatTime(_ timeInSeconds: Double) -> String {
        let minutes = Int(timeInSeconds) / 60
        let seconds = Int(timeInSeconds) % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
    
    private static var defaultGradient: LinearGradient {
        LinearGradient(
            colors: [
                Color(red: 0.8, green: 0.4, blue: 0.9),
                Color(red: 0.4, green: 0.6, blue: 1.0)
            ],
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
    }
}


#Preview {
    let sampleGradient = LinearGradient(
        colors: [
            Color(red: 0.8, green: 0.4, blue: 0.9),
            Color(red: 0.4, green: 0.6, blue: 1.0)
        ],
        startPoint: .topLeading,
        endPoint: .bottomTrailing
    )
    
    VStack(spacing: 20) {
        CreateAudioPlayer(
            songTitle: "Summertime (#1)",
            artworkGradient: sampleGradient,
            isPlaying: true,
            onPlayPause: { print("Play/Pause tapped") }
        )

        CreateAudioPlayer(
            songTitle: "Best Friend Forever",
            artworkGradient: sampleGradient,
            isPlaying: false,
            onPlayPause: { print("Play/Pause tapped") }
        )
    }
    .padding()
    .background(Constants.Colors.Background.primary)
}
