import SwiftUI
import AVFoundation

struct MusicPlayer: View {
    let track: Track
    @State private var isPlaying: Bool = false
    @State private var currentTime: Double = 0
    @State private var totalTime: Double = 0
    @State private var audioPlayer: AVAudioPlayer?
    @State private var videoPlayer: AVPlayer?
    @State private var timer: Timer?
    @State private var toggleObserver: NSObjectProtocol?
    @State private var showFullscreenVideo: Bool = false
    
    var body: some View {
        VStack(spacing: 12) {
            // Top section with artwork, info, and rating buttons
            HStack(spacing: 12) {
                // Artwork and track info
                HStack(spacing: 8) {
                    // Artwork or video (tappable for fullscreen)
                    Button(action: {
                        if track.badge == "Video" {
                            showFullscreenVideo = true
                        }
                        // For non-video tracks, we could add artwork fullscreen later
                    }) {
                        if track.badge == "Video" {
                            // Show video for video tracks with time tracking and audio
                            InlineVideoPlayer(
                                cornerRadius: 8,
                                onTimeUpdate: { current, duration in
                                    currentTime = current
                                    totalTime = duration
                                },
                                onPlayerReady: { player in
                                    videoPlayer = player
                                },
                                isMuted: false
                            )
                            .frame(width: 30, height: 36)
                        } else {
                            // Show static image for non-video tracks
                            Image(track.artworkName)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width: 30, height: 36)
                                .clipShape(RoundedRectangle(cornerRadius: 8))
                        }
                    }
                    .buttonStyle(PlainButtonStyle())
                    
                    // Track info
                    VStack(alignment: .leading, spacing: 2) {
                        Text(track.title)
                            .font(Constants.Typography.small)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .lineLimit(1)
                        
                        Text(track.genres.joined(separator: ", "))
                            .font(Constants.Typography.xSmallRegular)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                            .lineLimit(1)
                    }
                    
                    Spacer()
                }
                
                // Rating buttons (thumbs up/down)
                HStack(spacing: 16) {
                    Button(action: {
                        print("Thumbs up tapped")
                    }) {
                        Image("Icon/thumbs-up")
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 24, height: 24)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                    
                    Button(action: {
                        print("Thumbs down tapped")
                    }) {
                        Image("Icon/thumbs-down")
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 24, height: 24)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                }
            }
            
            // Bottom section with progress and controls
            VStack(spacing: 16) {
                // Progress bar with timestamps
                ZStack {
                    // Progress bar
                    VStack(spacing: 4) {
                        // Progress track
                        ZStack(alignment: .leading) {
                            // Background track
                            RoundedRectangle(cornerRadius: 2)
                                .fill(Color.white.opacity(0.1))
                                .frame(height: 4)
                            
                            // Progress fill
                            GeometryReader { geometry in
                                RoundedRectangle(cornerRadius: 2)
                                    .fill(Constants.Colors.Foreground.primary)
                                    .frame(width: totalTime > 0 ? CGFloat(currentTime / totalTime) * geometry.size.width : 0, height: 4)
                            }
                            .frame(height: 4)
                        }
                    }
                    
                    // Timestamps overlay
                    HStack {
                        Text(formatTime(currentTime))
                            .font(Constants.Typography.timecode)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                        
                        Spacer()
                        
                        Text(formatTime(totalTime))
                            .font(Constants.Typography.timecode)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                    .offset(y: 12) // Position below progress bar
                }
                
                // Control buttons
                HStack(spacing: 30) {
                    // Remix/Shuffle button
                    Button(action: {
                        print("Remix tapped")
                    }) {
                        Image("Icon/remix") // Need to check if this exists or suggest alternative
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 20, height: 20)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                    
                    // Previous track
                    Button(action: {
                        print("Previous tapped")
                    }) {
                        Image("Icon/previous-track")
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 24, height: 24)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                    
                    // Play/Pause button (larger, primary color)
                    Button(action: {
                        togglePlayback()
                    }) {
                        Image(isPlaying ? "Icon/pause" : "Icon/play")
                            .resizable()
                            .frame(width: 32, height: 32)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                    }
                    
                    // Next track
                    Button(action: {
                        print("Next tapped")
                    }) {
                        Image("Icon/next-track")
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 24, height: 24)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                    
                    // More options
                    Button(action: {
                        print("More tapped")
                    }) {
                        Image("Icon/more-horizontal")
                            .resizable()
                            .renderingMode(.template)
                            .frame(width: 24, height: 24)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                }
            }
        }
        .padding(12)
        .background(
            Constants.Colors.Background.Smoke.dense
                .background(.ultraThinMaterial)
        )
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .onAppear {
            setupAudioPlayer()
            // Auto-play when player first appears
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
                if track.badge == "Video" {
                    // Video auto-play is handled by InlineVideoPlayer
                    isPlaying = true
                    print("🎬 Video auto-playing on appear: \(track.title)")
                    // Broadcast initial play state
                    NotificationCenter.default.post(
                        name: NSNotification.Name("PlaybackStateChanged"),
                        object: nil,
                        userInfo: [
                            "trackId": track.id,
                            "isPlaying": true
                        ]
                    )
                    print("📡 Broadcasted initial video playing state for \(track.title)")
                } else if let player = audioPlayer, !isPlaying {
                    player.play()
                    startTimer()
                    isPlaying = true
                    print("🎵 Auto-playing on appear: \(track.title)")
                    // Broadcast initial play state
                    NotificationCenter.default.post(
                        name: NSNotification.Name("PlaybackStateChanged"),
                        object: nil,
                        userInfo: [
                            "trackId": track.id,
                            "isPlaying": true
                        ]
                    )
                    print("📡 Broadcasted initial playing state for \(track.title)")
                }
            }
            
            // Listen for toggle playback requests from thumbnail with proper observer management
            if let existingObserver = toggleObserver {
                NotificationCenter.default.removeObserver(existingObserver)
            }
            
            toggleObserver = NotificationCenter.default.addObserver(
                forName: NSNotification.Name("TogglePlayback"),
                object: nil,
                queue: .main
            ) { notification in
                if let userInfo = notification.userInfo,
                   let trackId = userInfo["trackId"] as? String {
                    print("🔔 MusicPlayer received TogglePlayback for trackId: \(trackId)")
                    print("🔍 MusicPlayer current track ID: \(track.id)")
                    if trackId == track.id {
                        print("✅ MusicPlayer toggling playback for \(track.title)")
                        togglePlayback()
                    }
                }
            }
        }
        .onChange(of: track.id) { _ in
            // When track changes, setup new audio and auto-play
            print("🔄 MusicPlayer track changed to: \(track.title) (ID: \(track.id))")
            stopPlayback() // Stop current playback first
            setupAudioPlayer()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                if track.badge == "Video" {
                    // Video auto-play is handled by InlineVideoPlayer
                    isPlaying = true
                    print("🎬 Auto-playing video track: \(track.title)")
                    // Broadcast auto-play state
                    NotificationCenter.default.post(
                        name: NSNotification.Name("PlaybackStateChanged"),
                        object: nil,
                        userInfo: [
                            "trackId": track.id,
                            "isPlaying": true
                        ]
                    )
                    print("📡 Broadcasted video playing state for \(track.title)")
                } else if let player = audioPlayer {
                    player.play()
                    startTimer()
                    isPlaying = true
                    print("🎵 Auto-playing track: \(track.title)")
                    // Broadcast auto-play state
                    NotificationCenter.default.post(
                        name: NSNotification.Name("PlaybackStateChanged"),
                        object: nil,
                        userInfo: [
                            "trackId": track.id,
                            "isPlaying": true
                        ]
                    )
                    print("📡 Broadcasted playing state for \(track.title)")
                }
            }
        }
        .onDisappear {
            stopPlayback()
            if let existingObserver = toggleObserver {
                NotificationCenter.default.removeObserver(existingObserver)
                toggleObserver = nil
            }
        }
        .fullScreenCover(isPresented: $showFullscreenVideo) {
            if let player = videoPlayer {
                FullscreenVideoPlayer(
                    player: player,
                    track: track,
                    isPresented: $showFullscreenVideo
                )
            }
        }
    }
    
    private func setupAudioPlayer() {
        // For video tracks, audio is handled by the video player itself
        // Only setup audio player for non-video tracks
        if track.badge != "Video" {
            setupLofiAudio()
        }
    }
    
    
    private func setupLofiAudio() {
        // Try to get lofi as data asset first
        if let asset = NSDataAsset(name: "lofi") {
            let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("lofi.mp3")
            do {
                // Remove existing temp file if it exists
                if FileManager.default.fileExists(atPath: tempURL.path) {
                    try FileManager.default.removeItem(at: tempURL)
                }
                try asset.data.write(to: tempURL)
                
                audioPlayer = try AVAudioPlayer(contentsOf: tempURL)
                audioPlayer?.prepareToPlay()
                totalTime = audioPlayer?.duration ?? 0
                print("🎵 Audio player setup complete from data asset. Duration: \(totalTime) seconds")
                return
            } catch {
                print("❌ Failed to write lofi data asset: \(error)")
            }
        }
        
        // Fallback to bundle resources
        if let url = Bundle.main.url(forResource: "lofi", withExtension: "mp3") {
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: url)
                audioPlayer?.prepareToPlay()
                totalTime = audioPlayer?.duration ?? 0
                print("🎵 Audio player setup complete from bundle. Duration: \(totalTime) seconds")
            } catch {
                print("❌ Error setting up audio player from bundle: \(error)")
            }
        } else {
            print("❌ Could not find lofi audio file in bundle or assets")
        }
    }
    
    private func togglePlayback() {
        if track.badge == "Video" {
            // Handle video playback
            guard let player = videoPlayer else { return }
            
            if isPlaying {
                player.pause()
            } else {
                player.play()
            }
            isPlaying.toggle()
        } else {
            // Handle audio playback
            guard let player = audioPlayer else { return }
            
            if isPlaying {
                player.pause()
                stopTimer()
            } else {
                player.play()
                startTimer()
            }
            isPlaying.toggle()
        }
        
        // Broadcast playback state change
        NotificationCenter.default.post(
            name: NSNotification.Name("PlaybackStateChanged"),
            object: nil,
            userInfo: [
                "trackId": track.id,
                "isPlaying": isPlaying
            ]
        )
    }
    
    private func stopPlayback() {
        audioPlayer?.stop()
        audioPlayer?.currentTime = 0
        isPlaying = false
        currentTime = 0
        stopTimer()
        
        // Broadcast stop state
        NotificationCenter.default.post(
            name: NSNotification.Name("PlaybackStateChanged"),
            object: nil,
            userInfo: [
                "trackId": track.id,
                "isPlaying": false
            ]
        )
    }
    
    private func startTimer() {
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
            guard let player = audioPlayer else { return }
            currentTime = player.currentTime
            
            // Stop when track ends
            if !player.isPlaying && currentTime > 0 {
                isPlaying = false
                stopTimer()
            }
        }
    }
    
    private func stopTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    private func formatTime(_ timeInSeconds: Double) -> String {
        let minutes = Int(timeInSeconds) / 60
        let seconds = Int(timeInSeconds) % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
}

#Preview {
    let sampleTrack = Track(
        title: "Magical Vibes (Remix)",
        genres: ["Experimental Rock", "Art Rock", "Dance", "Hip-hop"],
        artworkName: "Artwork/1",
        badge: "Remix"
    )
    
    MusicPlayer(track: sampleTrack)
        .padding()
        .background(Constants.Colors.Background.primary)
}
