//
//  NowPlayingCard.swift
//  vibes
//
//  Created by Claude on 11/7/25.
//

import SwiftUI
import NukeUI

struct NowPlayingCard: View {
    let metadata: AudioMetadata
    let isPlaying: Bool
    let onPlayPause: () -> Void
    let onNext: () -> Void
    let onCardTap: (() -> Void)?
    
    @State private var visualizerHeights: [CGFloat] = [8, 12, 6, 10]
    @State private var visualizerTimer: Timer?
    @State private var rotationAngle: Double = 0
    
    var body: some View {
        // Audio Info Card (60px height from Figma) - EXACT copy from hooks tab
        HStack(spacing: 8) { // gap-2 = 8px
            // Album Art with Visualizer (40x40px) - Tappable to open Omniplayer
            ZStack {
                // Album artwork - rotating only when playing
                ZStack {
                    // Debug background circle
                    Circle()
                        .fill(Color.purple)
                        .frame(width: 40, height: 40)
                    
                    // Actual artwork - handle both local assets and URLs
                    Group {
                        if metadata.artworkName.hasPrefix("http") {
                            LazyImage(url: URL(string: metadata.artworkName)) { state in
                                if let image = state.image {
                                    image
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                                } else {
                                    Image("Artwork/2") // Fallback to local asset
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                                }
                            }
                        } else {
                            Image(metadata.artworkName)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                        }
                    }
                    .frame(width: 40, height: 40)
                    .clipShape(Circle())
                }
                .rotationEffect(.degrees(rotationAngle))
                
                // Mini audio visualizer bars (14.4px width from Figma) - overlay with transparency
                HStack(spacing: 2) {
                    ForEach(0..<4, id: \.self) { index in
                        Rectangle()
                            .fill(.white.opacity(0.6)) // More transparent so artwork shows through clearly
                            .frame(width: 2, height: visualizerHeights[index])
                            .clipShape(RoundedRectangle(cornerRadius: 20))
                            .animation(.easeInOut(duration: 0.3), value: visualizerHeights[index])
                    }
                }
                .frame(width: 14.4, height: 12)
                .allowsHitTesting(false) // Don't block touch events to artwork
            }
            .frame(width: 40, height: 40)
            
            // Song Info (156px width from Figma)
            VStack(alignment: .leading, spacing: 2) { // gap-0.5 = 2px
                HStack {
                    Text(metadata.title)
                        .font(.custom("PP Neue Montreal", size: 14))
                        .foregroundColor(.white)
                        .shadow(color: .black.opacity(0.25), radius: 8, x: 0, y: 0)
                        .lineLimit(1)
                    Spacer()
                }
                
                HStack {
                    Text(metadata.artistName)
                        .font(.custom("PP Neue Montreal", size: 12))
                        .foregroundColor(.white.opacity(0.5))
                        .lineLimit(1)
                    Spacer()
                }
                .frame(height: 16) // h-4 = 16px
            }
            .contentShape(Rectangle())
            .onTapGesture {
                onCardTap?()
            }
            
            Spacer()
            
            // Action buttons (44px height from Figma) - Don't trigger parent tap
            HStack(spacing: 8) { // Reduced spacing between icons
                // Play/Pause Button - Only this button controls playback
                Button(action: onPlayPause) {
                    Image(systemName: isPlaying ? "pause.fill" : "play.fill")
                        .font(.system(size: 16, weight: .medium)) // Reduced from 20 to 16
                        .foregroundColor(.white)
                        .frame(width: 44, height: 44)
                }
                
                // Next Button - Opens Omniplayer instead of skipping
                Button(action: { onCardTap?() }) {
                    Image(systemName: "forward.fill")
                        .font(.system(size: 14, weight: .medium)) // Reduced from 18 to 14
                        .foregroundColor(.white)
                        .frame(width: 44, height: 44)
                }
            }
            .frame(height: 44)
            .allowsHitTesting(true) // Buttons handle their own taps
        }
        .padding(.horizontal, 8) // px-2 = 8px horizontal
        .padding(.vertical, 12) // py-3 = 12px vertical
        .frame(height: 60) // Fixed height from Figma
        .frame(maxWidth: .infinity) // Full width like hooks tab
        .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 40))
        .contentShape(Rectangle()) // Make entire card tappable
        .onTapGesture {
            onCardTap?()
        }
        .gesture(
            DragGesture()
                .onEnded { value in
                    // Detect upward swipe
                    if value.translation.height < -50 && abs(value.translation.height) > abs(value.translation.width) {
                        onCardTap?()
                    }
                }
        )
        .onAppear {
            startAnimations() // Always start animations, rotation controlled by isPlaying state
            if isPlaying {
                // Start rotation if already playing
                withAnimation(.linear(duration: 10).repeatForever(autoreverses: false)) {
                    rotationAngle = 360
                }
            }
        }
        .onDisappear {
            stopAnimations()
        }
        .onChange(of: isPlaying) { _, newValue in
            if newValue {
                // Start continuous rotation
                withAnimation(.linear(duration: 10).repeatForever(autoreverses: false)) {
                    rotationAngle = 360
                }
            } else {
                // Stop rotation at current position
                withAnimation(.linear(duration: 0)) {
                    rotationAngle = rotationAngle.truncatingRemainder(dividingBy: 360)
                }
            }
        }
    }
    
    private func startAnimations() {
        // Start visualizer animation
        visualizerTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: true) { _ in
            withAnimation(.easeInOut(duration: 0.3)) {
                for i in 0..<visualizerHeights.count {
                    visualizerHeights[i] = CGFloat.random(in: 4...12)
                }
            }
        }
    }
    
    private func stopAnimations() {
        visualizerTimer?.invalidate()
        visualizerTimer = nil
    }
}

#Preview {
    VStack {
        Spacer()
        
        NowPlayingCard(
            metadata: AudioMetadata(
                title: "Nocturnal Apparition",
                artistName: "DreamsOfDust",
                playCount: "12.1k",
                artworkName: "Artwork/2"
            ),
            isPlaying: true,
            onPlayPause: {
                print("Play/Pause tapped")
            },
            onNext: {
                print("Next tapped")
            },
            onCardTap: {
                print("Card tapped - expand player")
            }
        )
        .padding(.horizontal, 16)
        .padding(.bottom, 100) // Above nav bar
    }
    .background(
        LinearGradient(
            gradient: Gradient(colors: [.purple, .blue]),
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
    )
    .ignoresSafeArea()
}
