//
//  SongPlayerView.swift
//  vibes
//
//  Created by Claude Code on 1/6/25.
//

import SwiftUI
import NukeUI

struct SongPlayerView: View {
    @State private var isPlaying = false
    @State private var visualizerHeights: [CGFloat] = [5, 6, 12, 10]
    @State private var showRemixSelectionSheet = false
    @State private var showRemixCreate = false
    @State private var showExtendView = false
    @State private var selectedRemixType = "Cover"
    @ObservedObject private var generationManager = SongGenerationManager.shared
    
    @EnvironmentObject private var tweaksManager: TweaksManager
    @EnvironmentObject private var appState: AppState
    @EnvironmentObject private var tabBarState: TabBarState
    
    let song: UploadedSong
    let bottomSafeArea: CGFloat

    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // Background with color sampled from artwork
                LazyImage(url: URL(string: song.imageURL ?? "")) { state in
                    if let image = state.image {
                        image
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: geometry.size.width, height: geometry.size.height)
                            .blur(radius: 100)
                            .opacity(0.6)
                            .clipShape(Rectangle())
                    }
                }

                // Darker overlay for better contrast
                Color.black.opacity(0.3)
                    .clipShape(Rectangle())

                // Large spinning circular artwork in center
                ZStack {
                    LazyImage(url: URL(string: song.imageURL ?? "")) { state in
                        if let container = state.imageContainer {
                            RotatingImageView(image: container.image, rpm: 4)
                                .frame(width: geometry.size.width - 48, height: geometry.size.width - 48)
                        }
                    }
                    .clipShape(Circle())
                    .shadow(color: .black.opacity(0.3), radius: 20, x: 0, y: 10)
                }
                .onTapGesture {
                    togglePlayPause()
                }

                // Right side actions positioned 8px from right edge
                VStack {
                    Spacer()

                    HStack {
                        Spacer()

                        VStack(spacing: 10) { // gap-2.5 = 10px

                            // Remix
                            VStack(spacing: 4) { // gap-1 = 4px
                                PlayerIconButton(iconName: "Icon/remix") {
                                    showRemixSelectionSheet = true
                                }

                                Text("REMIX")
                                    .font(.custom("Input Sans", size: 10).weight(.medium))
                                    .foregroundColor(.white)
                                    .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 0)
                            }


                            // Like Button
                            VStack(spacing: 4) { // gap-1 = 4px
                                PlayerIconButton(iconName: "Icon/heart") {
                                    print("Like button tapped")
                                }

                                Text("128")
                                    .font(.custom("Input Sans", size: 10).weight(.medium))
                                    .foregroundColor(.white)
                                    .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 0)
                            }

                            // Comment Button
                            VStack(spacing: 4) {
                                PlayerIconButton(iconName: "Icon/comment") {
                                    print("Comment button tapped")
                                }

                                Text("24")
                                    .font(.custom("Input Sans", size: 10).weight(.medium))
                                    .foregroundColor(.white)
                                    .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 0)
                            }

                            // Share Button
                            VStack(spacing: 4) {
                                PlayerIconButton(iconName: "Icon/share-arrow") {
                                    print("Share button tapped")
                                }

                                Text("SHARE")
                                    .font(.custom("Input Sans", size: 10).weight(.medium))
                                    .foregroundColor(.white)
                                    .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 0)
                            }

                            // More Button
                            PlayerIconButton(iconName: "Icon/more-horizontal") {
                                print("More button tapped")
                            }
                        }
                        .padding(.trailing)
                    }
                    // Keep right-side actions above the bottom safe area and the attribution section
                    .padding(.bottom, bottomSafeArea + 32 + (tweaksManager.isLiquidGlassTabBarEnabled ? 0 : 70))
                    .animation(.easeInOut(duration: 0.2), value: bottomSafeArea)
                }

                // Bottom content container
                VStack(spacing: 0) {
                    Spacer()

                    // Bottom Attribution Section
                    VStack(alignment: .leading, spacing: 8) { // gap-3 = 12px
                        // Artist profile with follow button
                        HStack(spacing: 8) {
                            // Profile image (26x26)
                            Image("Avatar/8")
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width: 26, height: 26)
                                .clipShape(Circle())

                            // Username
                            Text(song.artistName)
                                .font(.custom("PP Neue Montreal", size: 16).weight(.medium))
                                .foregroundColor(.white)
                                .shadow(color: .black.opacity(0.25), radius: 8, x: 0, y: 0)
                                .lineLimit(1)

                            // Follow button
                            Button(action: {
                                print("Follow button tapped")
                            }) {
                                Text("Follow")
                                    .font(.custom("PP Neue Montreal", size: 12).weight(.medium))
                                    .foregroundColor(Constants.ForegroundPrimary)
                                    .tracking(0.24)
                                    .padding(.horizontal, 8)
                                    .padding(.vertical, 2)
                            }
                            .frame(height: 22)
                            .overlay(
                                RoundedRectangle(cornerRadius: 50)
                                    .stroke(.white, lineWidth: 1)
                            )

                            Spacer()
                        }

                        if let rewrittenPrompt = song.rewrittenPrompt,
                           !rewrittenPrompt.isEmpty {
                            Text(rewrittenPrompt)
                                .font(Constants.Typography.small)
                                .lineHeight(.exact(points: 20))
                                .foregroundStyle(.white.opacity(0.8))
                                .shadow(color: .black.opacity(0.25), radius: 8, x: 0, y: 0)
                                .lineLimit(3)
                                .padding(.trailing, 80)
                        }

                        if !tweaksManager.isLiquidGlassTabBarEnabled {
                            // Audio Info Card (60px height from Figma)
                            HStack(spacing: 8) { // gap-2 = 8px
                                // Album Art with Visualizer (40x40px)
                                ZStack {
                                    LazyImage(url: URL(string: song.imageURL ?? "")) { state in
                                        if let image = state.image {
                                            image
                                                .resizable()
                                                .aspectRatio(contentMode: .fill)
                                        }
                                    }
                                    .frame(width: 40, height: 40)
                                    .clipShape(RoundedRectangle(cornerRadius: 60))

                                    // Mini audio visualizer bars (14.4px width from Figma)
                                    HStack(spacing: 2) {
                                        ForEach(0..<4, id: \.self) { index in
                                            Rectangle()
                                                .fill(.white)
                                                .frame(width: 2, height: visualizerHeights[index])
                                                .clipShape(RoundedRectangle(cornerRadius: 20))
                                                .animation(.easeInOut(duration: 0.3), value: visualizerHeights[index])
                                        }
                                    }
                                    .frame(width: 14.4, height: 12)
                                }
                                .frame(width: 40, height: 40)

                                // Song Info (156px width from Figma)
                                VStack(alignment: .leading, spacing: 2) { // gap-0.5 = 2px
                                    Text(song.name)
                                        .font(.custom("PP Neue Montreal", size: 14))
                                        .foregroundColor(.white)
                                        .shadow(color: .black.opacity(0.25), radius: 8, x: 0, y: 0)
                                        .lineLimit(1)

                                    HStack(spacing: 4) { // gap-1 = 4px
                                        HStack(spacing: 4) {
                                            // Play icon (10x14px from Figma)
                                            Image(systemName: "play.fill")
                                                .font(.system(size: 8))
                                                .foregroundColor(.white.opacity(0.5))
                                                .frame(width: 10, height: 14)

                                            Text("12.1k")
                                                .font(.custom("PP Neue Montreal", size: 12))
                                                .foregroundColor(.white.opacity(0.5))
                                        }

                                        Text("·")
                                            .font(.custom("PP Neue Montreal", size: 12))
                                            .foregroundColor(.white.opacity(0.75))

                                        Text("DreamsOfDust")
                                            .font(.custom("PP Neue Montreal", size: 12))
                                            .foregroundColor(.white.opacity(0.5))
                                    }
                                    .frame(height: 16) // h-4 = 16px
                                }

                                Spacer()

                                // Action buttons (44px height from Figma)
                                HStack(spacing: 8) { // gap-2 = 8px

                                    Button(action: {
                                        showRemixSelectionSheet = true
                                    }) {
                                        HStack(spacing: 4) {
                                            Image("Icon/plus")
                                                .resizable()
                                                .aspectRatio(contentMode: .fit)
                                                .frame(width: 16, height: 16)

                                            Text("SAVE")
                                                .font(.custom("Input Sans", size: 12).weight(.medium))
                                        }
                                        .foregroundColor(Color(hex: "#F7F4EF"))
                                        .padding(.horizontal, 16)
                                        .padding(.vertical, 0)
                                        .frame(height: 44)
                                        .background(
                                            RoundedRectangle(cornerRadius: 100)
                                                .fill(Constants.Colors.Background.Fog.thick)
                                        )
                                        .clipShape(RoundedRectangle(cornerRadius: 100))
                                    }
                                }
                                .frame(height: 44) // Fixed height from Figma
                            }
                            .padding(.horizontal, 8) // px-2 = 8px horizontal
                            .padding(.vertical, 12) // py-3 = 12px vertical
                            .frame(height: 60) // Fixed height from Figma
                            .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 40))
                        }
                    }
                }
                .padding(.horizontal)
                // Keep the bottom attribution section above the home indicator,
                // and push it up further when the tab bar accessory is expanded.
                .padding(.bottom, bottomSafeArea + 32)
                .animation(.easeInOut(duration: 0.2), value: bottomSafeArea)
            }
        }
        .background(Color.black)
        // Allow content to extend under the status bar, but not below the bottom safe area
        .ignoresSafeArea(.container, edges: [.top])
        .sheet(isPresented: $showRemixSelectionSheet) {
            RemixSelectionView(song: song)
        }
        .sheet(isPresented: $showRemixCreate) {
            RemixCoverView(
                isPresented: $showRemixCreate,
                originalTrackTitle: song.name,
                remixType: selectedRemixType
            ) {
                // Back button tapped - reopen remix selection sheet
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    showRemixSelectionSheet = true
                }
            }
            .presentationDetents([.large])
            .presentationDragIndicator(.hidden)
            .presentationBackground {
                Constants.Colors.Background.Smoke.dense
                    .background(.ultraThinMaterial)
            }
        }
        .sheet(isPresented: $showExtendView) {
            RemixExtendView(
                isPresented: $showExtendView,
                originalTrackTitle: song.name
            ) {
                // Back button tapped - reopen remix selection sheet
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    showRemixSelectionSheet = true
                }
            }
            .presentationDetents([.large])
            .presentationDragIndicator(.hidden)
            .presentationBackground {
                Constants.Colors.Background.Smoke.dense
                    .background(.ultraThinMaterial)
            }
        }
        .onAppear {
            print("onappear \(song.artistName)")
//            startVisualizerAnimation()

//            // Defer animation start to ensure view is fully laid out
//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
//                startArtworkRotation()
//            }
        }
        .onDisappear {
            
        }
    }

    private func togglePlayPause() {
        isPlaying.toggle()
        if isPlaying {
//            startArtworkRotation()
        } else {
//            // Pause rotation
//            withAnimation(.linear(duration: 0)) {
//                artworkRotation = artworkRotation.truncatingRemainder(dividingBy: 360)
//            }
        }
    }

    private func startVisualizerAnimation() {
        Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { _ in
            withAnimation(.easeInOut(duration: 0.3)) {
                for i in 0..<visualizerHeights.count {
                    visualizerHeights[i] = CGFloat.random(in: 4...12)
                }
            }
        }
    }
}

#Preview {
    SongPlayerView(
        song: UploadedSong(id: "123", name: "test song", artistName: "mozart", artistId: "123", createdAt: .now),
        bottomSafeArea: 0)
}
