//
//  VideoPlayerView.swift
//  vibes
//
//  Created by Claude Code on 7/30/25.
//

import SwiftUI
import AVKit

struct VideoPlayerView: View {
    @State private var player: AVPlayer?
    @State private var isPlaying = false
    @State private var showControls = false
    @State private var visualizerHeights: [CGFloat] = [5, 6, 12, 10]
    @State private var artworkRotation: Double = 0
    @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

    let trackTitle: String
    let videoUrl: String

    init(trackTitle: String = "Nocturnal Apparition", videoUrl: String = "hook") {
        self.trackTitle = trackTitle
        self.videoUrl = videoUrl
    }
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // Video Player Background
                if let player = player {
                    CustomVideoPlayerView(player: player)
                        .frame(width: geometry.size.width, height: geometry.size.height)
                        .onTapGesture {
                            togglePlayPause()
                        }
                } else {
                    // Placeholder when no video
                    Rectangle()
                        .fill(Color.black)
                        .frame(width: geometry.size.width, height: geometry.size.height)
                        .overlay(
                            VStack {
                                Image(systemName: "play.circle.fill")
                                    .font(.system(size: 64))
                                    .foregroundColor(.white.opacity(0.8))

                                Text("No video selected")
                                    .font(Constants.Typography.mediumRegular)
                                    .foregroundColor(.white.opacity(0.8))
                                    .padding(.top, 8)
                            }
                        )
                }

                // 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") {
                                    print("Remix button tapped")
                                }
                                
                                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, 8) // 8px from right edge
                    }
                    .padding(.bottom, 108) // Position above the bottom content
                }
                
                // Bottom content container
                VStack(spacing: 0) {
                    Spacer()
                    
                    // Bottom Attribution Section
                    VStack(spacing: 12) { // 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("DreamsOfDust")
                                .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()
                        }
                        
                        // Audio Info Card (60px height from Figma)
                        HStack(spacing: 8) { // gap-2 = 8px
                            // Album Art with Visualizer (40x40px)
                            ZStack {
                                Image("Artwork/2")
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(width: 40, height: 40)
                                    .clipShape(RoundedRectangle(cornerRadius: 60))
                                    .rotationEffect(.degrees(artworkRotation))
                                
                                // 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(spacing: 2) { // gap-0.5 = 2px
                                Text("Nocturnal Apparition")
                                    .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(.bottom, 12)
                .padding(.horizontal, 8)
                
            }
        }
        .background(Color.black)
        .ignoresSafeArea(.container, edges: [.all])
        .sheet(isPresented: $showRemixCreate) {
            RemixCoverView(
                isPresented: $showRemixCreate,
                originalTrackTitle: trackTitle,
                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: trackTitle
            ) {
                // 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: $generationManager.showWorkspace) {
            WorkspaceView(
                onDismiss: {
                    generationManager.closeWorkspace()
                },
                onTrackTap: { track in
                    print("Track tapped: \(track.title)")
                },
                onEditPrompt: {
                    generationManager.startEditingMode()
                }
            )
            .presentationDetents([.large])
            .presentationDragIndicator(.hidden)
            .presentationBackground {
                Color(Constants.Colors.Background.secondary)
            }
        }
        .sheet(isPresented: $generationManager.showCreateSheet) {
            CreateView()
                .presentationDetents([.large])
                .presentationDragIndicator(.hidden)
                .presentationBackground {
                    Color(Constants.Colors.Background.secondary)
                }
        }
        .onAppear {
            setupPlayer()
            startVisualizerAnimation()
            startArtworkRotation()
            
            // Listen for pause notifications
            NotificationCenter.default.addObserver(
                forName: NSNotification.Name("PauseHooksVideo"),
                object: nil,
                queue: .main
            ) { _ in
                self.pauseVideo()
            }
        }
        .onDisappear {
            player?.pause()
            // Remove notification observers
            NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: player?.currentItem)
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name("PauseHooksVideo"), object: nil)
        }
    }
    
    private func setupPlayer() {
        // Try different ways to load the video
        var videoURL: URL?

        // Method 1: Try loading from main bundle
        videoURL = Bundle.main.url(forResource: videoUrl, withExtension: "mp4")

        // Method 2: Try with NSDataAsset (for dataset files)
        if videoURL == nil {
            if let dataAsset = NSDataAsset(name: videoUrl) {
                // Write the data to a temporary file and create URL from it
                let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("\(videoUrl).mp4")
                do {
                    try dataAsset.data.write(to: tempURL)
                    videoURL = tempURL
                    print("✅ Created temporary video file at: \(tempURL)")
                } catch {
                    print("❌ Failed to write video data to temp file: \(error)")
                }
            } else {
                print("❌ Could not load \(videoUrl) data asset")
            }
        }

        // Method 3: Debug - list all available resources
        if videoURL == nil {
            print("🔍 Searching for video files in bundle...")
            if let bundlePath = Bundle.main.resourcePath {
                let fileManager = FileManager.default
                do {
                    let allFiles = try fileManager.contentsOfDirectory(atPath: bundlePath)
                    let videoFiles = allFiles.filter { $0.contains(videoUrl) || $0.hasSuffix(".mp4") || $0.hasSuffix(".mov") }
                    print("📁 Found potential video files: \(videoFiles)")
                } catch {
                    print("❌ Error listing bundle contents: \(error)")
                }
            }
        }
        
        guard let url = videoURL else {
            print("❌ Could not find \(videoUrl).mp4 video")
            return
        }
        
        print("✅ Loading video from: \(url)")
        player = AVPlayer(url: url)
        
        // Enable looping
        player?.actionAtItemEnd = .none
        
        // Add notification observer for when video ends to restart it
        NotificationCenter.default.addObserver(
            forName: .AVPlayerItemDidPlayToEndTime,
            object: player?.currentItem,
            queue: .main
        ) { _ in
            self.player?.seek(to: .zero)
            self.player?.play()
        }
        
        player?.play()
        isPlaying = true
    }
    
    private func togglePlayPause() {
        guard let player = player else { return }
        
        if isPlaying {
            player.pause()
        } else {
            player.play()
        }
        isPlaying.toggle()
    }
    
    private func pauseVideo() {
        guard let player = player else { return }
        player.pause()
        isPlaying = false
    }
    
    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)
                }
            }
        }
    }
    
    private func startArtworkRotation() {
        withAnimation(.linear(duration: 10).repeatForever(autoreverses: false)) {
            artworkRotation = 360
        }
    }
    

}

// Custom video player view that hides default controls
struct CustomVideoPlayerView: UIViewRepresentable {
    let player: AVPlayer

    func makeCoordinator() -> Coordinator {
        Coordinator()
    }

    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        view.backgroundColor = .black

        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.videoGravity = .resizeAspectFill
        view.layer.addSublayer(playerLayer)

        // Store the player layer in the coordinator
        context.coordinator.playerLayer = playerLayer

        return view
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        // Update the player layer frame when the view size changes
        DispatchQueue.main.async {
            context.coordinator.playerLayer?.frame = uiView.bounds
        }
    }

    class Coordinator {
        var playerLayer: AVPlayerLayer?
    }
}

#Preview {
    VideoPlayerView()
}
