import SwiftUI

struct TrackCell: View {
    let track: Track
    let onTrackTap: (() -> Void)?
    let onMoreTap: () -> Void
    let isCurrentlyPlaying: Bool
    let artworkGradient: LinearGradient?
    @State private var isActuallyPlaying: Bool = false
    @State private var observer: NSObjectProtocol?

    init(track: Track, onTrackTap: (() -> Void)? = nil, onMoreTap: @escaping () -> Void, isCurrentlyPlaying: Bool = false, artworkGradient: LinearGradient? = nil) {
        self.track = track
        self.onTrackTap = onTrackTap
        self.onMoreTap = onMoreTap
        self.isCurrentlyPlaying = isCurrentlyPlaying
        self.artworkGradient = artworkGradient
    }
    
    var body: some View {
        Button(action: {
            onTrackTap?()
        }) {
            HStack(spacing: 0) {
                // Left content
                HStack(spacing: 8) {
                // Album artwork or video (56x56px - square)
                ZStack {
                    if track.badge == "Video" && isCurrentlyPlaying {
                        // Show muted video when it's a video track and currently playing
                        InlineVideoPlayer(cornerRadius: 8, isMuted: true)
                            .frame(width: 56, height: 56)
                    } else if let gradient = artworkGradient {
                        // Show shader artwork with gradient
                        ArtworkShader(gradient: gradient, isAlive: isCurrentlyPlaying)
                            .frame(width: 56, height: 56)
                            .cornerRadius(8)
                    } else {
                        // Fallback to static image
                        Image(track.artworkName)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 56, height: 56)
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                    }

                    // Dark overlay and play/pause icon when currently playing
                    if isCurrentlyPlaying {
                        RoundedRectangle(cornerRadius: 8)
                            .fill(Color.black.opacity(0.5))
                            .frame(width: 56, height: 56)

                        Button(action: {
                            // Toggle playback state via notification
                            NotificationCenter.default.post(
                                name: NSNotification.Name("TogglePlayback"),
                                object: nil,
                                userInfo: ["trackId": track.id]
                            )
                        }) {
                            Image(isActuallyPlaying ? "Icon/pause" : "Icon/play")
                                .resizable()
                                .renderingMode(.template)
                                .foregroundColor(.white)
                                .frame(width: 24, height: 24)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
                
                // Track information
                VStack(alignment: .leading, spacing: 4) {
                    // Track title with badge
                    HStack(spacing: 4) {
                        Text(track.title)
                            .font(.custom("PP Neue Montreal", size: 14))
                            .foregroundColor(isCurrentlyPlaying ? Constants.Colors.Accent.brand : Color(hex: "#FEFEFE"))
                            .tracking(0.28)
                            .lineLimit(1)
                        
                        if let badge = track.badge {
                            TrackBadge(text: badge)
                        }
                        
                        Spacer()
                    }
                    
                    // Genres
                    Text(track.genres.joined(separator: ", "))
                        .font(.custom("PP Neue Montreal", size: 12))
                        .foregroundColor(Color.white.opacity(0.7))
                        .tracking(0.24)
                        .lineLimit(1)
                        .frame(maxWidth: 220, alignment: .leading)
                }
                .padding(.vertical, 6)
            }
            
            Spacer()
            
            // More button
            Button(action: onMoreTap) {
                Image(systemName: "ellipsis")
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(Constants.Colors.Foreground.inactive)
                    .frame(width: 24, height: 24)
            }
            }
            .padding(0)
            .frame(height: 56)
            .background(
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color.clear)
            )
        }
        .buttonStyle(PlainButtonStyle())
        .onChange(of: isCurrentlyPlaying) { newValue in
            print("🔄 TrackCell isCurrentlyPlaying changed for \(track.title): \(newValue)")
            if newValue {
                // When this track becomes the currently playing track, set it as actually playing
                isActuallyPlaying = true
                print("✅ Set \(track.title) as actually playing")
            } else {
                // When this track is no longer the currently playing track, set it as not playing
                isActuallyPlaying = false
                print("❌ Set \(track.title) as not playing")
            }
        }
        .onAppear {
            print("👀 TrackCell appeared for: \(track.title) (ID: \(track.id))")
            // Set initial playing state
            isActuallyPlaying = isCurrentlyPlaying
            print("🎵 Initial state for \(track.title): isCurrentlyPlaying=\(isCurrentlyPlaying), isActuallyPlaying=\(isActuallyPlaying)")
            
            // Remove any existing observer first
            if let existingObserver = observer {
                NotificationCenter.default.removeObserver(existingObserver)
            }
            
            // Listen for playback state changes with proper observer management
            observer = NotificationCenter.default.addObserver(
                forName: NSNotification.Name("PlaybackStateChanged"),
                object: nil,
                queue: .main
            ) { notification in
                if let userInfo = notification.userInfo,
                   let trackId = userInfo["trackId"] as? String,
                   let playing = userInfo["isPlaying"] as? Bool {
                    print("🔔 Received PlaybackStateChanged for trackId: \(trackId), playing: \(playing)")
                    print("🔍 Comparing with current track ID: \(track.id)")
                    if trackId == track.id {
                        isActuallyPlaying = playing
                        print("✅ TrackCell updated play state for \(track.title): \(playing)")
                    } else {
                        // If this track is not the one playing, make sure it shows as not playing
                        if isActuallyPlaying {
                            isActuallyPlaying = false
                            print("❌ TrackCell \(track.title) set to not playing (different track)")
                        }
                    }
                }
            }
        }
        .onDisappear {
            print("👄 TrackCell disappeared for: \(track.title)")
            if let existingObserver = observer {
                NotificationCenter.default.removeObserver(existingObserver)
                observer = nil
            }
        }
    }
}

struct TrackBadge: View {
    let text: String
    
    var body: some View {
        Text(text)
            .font(.custom("PP Neue Montreal", size: 12))
            .foregroundColor(Constants.Colors.Foreground.primary)
            .tracking(0.24)
            .padding(.horizontal, 4)
            .padding(.vertical, 0)
            .background(
                RoundedRectangle(cornerRadius: 4)
                    .fill(Color.white.opacity(0.1))
            )
    }
}

struct Track {
    let id: String
    let title: String
    let genres: [String]
    let artworkName: String
    let badge: String?
    
    init(id: String = UUID().uuidString, title: String, genres: [String], artworkName: String, badge: String? = nil) {
        self.id = id
        self.title = title
        self.genres = genres
        self.artworkName = artworkName
        self.badge = badge
    }
}

#Preview {
    VStack(spacing: 12) {
        TrackCell(
            track: Track(
                title: "Magical Vibes (Remix)",
                genres: ["Experimental Rock", "Art Rock", "Dance", "Hip-hop"],
                artworkName: "Artwork/1",
                badge: "Cover"
            )
        ) {
            print("More tapped")
        }
        
        TrackCell(
            track: Track(
                title: "Another Track",
                genres: ["Electronic", "Ambient"],
                artworkName: "Artwork/2",
                badge: nil
            )
        ) {
            print("More tapped")
        }
        
        TrackCell(
            track: Track(
                title: "Long Track Title That Should Truncate",
                genres: ["Pop", "Rock", "Alternative", "Indie", "Electronic"],
                artworkName: "Artwork/3",
                badge: "Remix"
            )
        ) {
            print("More tapped")
        }
    }
    .padding()
    .background(Constants.Colors.Background.primary)
}