import SwiftUI
import AVKit

struct FullscreenPlayerView: View {
    @Binding var isPresented: Bool
    let track: Track
    @State private var player: AVPlayer?
    
    var body: some View {
        ZStack {
            // Always show black background
            Color.black
                .ignoresSafeArea()
            
            // Always show close button and track info for debugging
            VStack {
                HStack {
                    // Close button
                    Button(action: {
                        print("🔴 Close button tapped")
                        isPresented = false
                    }) {
                        Image(systemName: "xmark")
                            .font(.system(size: 20, weight: .bold))
                            .foregroundColor(.white)
                    }
                    .frame(width: 44, height: 44)
                    .background(Color.red.opacity(0.8))
                    .clipShape(Circle())
                    
                    Spacer()
                    
                    // Track info
                    VStack(alignment: .trailing, spacing: 4) {
                        Text(track.title)
                            .font(.system(size: 16, weight: .bold))
                            .foregroundColor(.white)
                            .lineLimit(1)
                        
                        Text("DEBUG: Fullscreen View Loaded")
                            .font(.system(size: 12))
                            .foregroundColor(.green)
                            .lineLimit(1)
                    }
                }
                .padding(.horizontal, 20)
                .padding(.top, 20)
                
                Spacer()
                
                // Debug info in center
                VStack(spacing: 20) {
                    Text("Player Status: \(player != nil ? "Loaded" : "Loading...")")
                        .font(.system(size: 18, weight: .medium))
                        .foregroundColor(.white)
                    
                    if let player = player {
                        VideoPlayer(player: player)
                            .frame(width: 300, height: 400)
                            .clipShape(RoundedRectangle(cornerRadius: 12))
                    } else {
                        // Loading state
                        VStack(spacing: 16) {
                            ProgressView()
                                .scaleEffect(2.0)
                                .progressViewStyle(CircularProgressViewStyle(tint: .white))
                            
                            Text("Loading video...")
                                .font(.system(size: 16))
                                .foregroundColor(.white)
                        }
                    }
                }
                
                Spacer()
            }
        }
        .onAppear {
            print("🎬 FullscreenPlayerView appeared!")
            setupPlayer()
        }
        .onDisappear {
            print("🎬 FullscreenPlayerView disappeared!")
            player?.pause()
            player = nil
        }
    }
    
    private func setupPlayer() {
        print("🎬 FullscreenPlayerView - Setting up player for track: \(track.title)")
        
        // Try to get sunohook_edited video
        guard let videoURL = getSunoHookEditedURL() else {
            print("❌ Could not find sunohook_edited video")
            return
        }
        
        print("✅ Found video URL: \(videoURL.absoluteString)")
        
        let playerItem = AVPlayerItem(url: videoURL)
        let newPlayer = AVPlayer(playerItem: playerItem)
        
        // Set the player first
        self.player = newPlayer
        print("✅ Player assigned to state variable")
        
        // Auto-play
        newPlayer.play()
        print("▶️ Started playing sunohook_edited video")
    }
    
    private func getSunoHookEditedURL() -> URL? {
        print("🔍 Searching for sunohook_edited video...")
        
        // Try as data asset first
        if let asset = NSDataAsset(name: "sunohook_edited") {
            print("✅ Found sunohook_edited data asset")
            let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("sunohook_edited.mov")
            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)
                print("✅ Created temp file at: \(tempURL)")
                return tempURL
            } catch {
                print("❌ Failed to write sunohook_edited data asset: \(error)")
            }
        } else {
            print("❌ No sunohook_edited data asset found")
        }
        
        // Try bundle resources
        if let url = Bundle.main.url(forResource: "sunohook_edited", withExtension: "mov") {
            print("✅ Found sunohook_edited.mov in bundle")
            return url
        } else if let url = Bundle.main.url(forResource: "sunohook_edited", withExtension: "mp4") {
            print("✅ Found sunohook_edited.mp4 in bundle") 
            return url
        } else {
            print("❌ No sunohook_edited found in bundle resources")
        }
        
        print("❌ sunohook_edited video not found anywhere")
        print("🔄 Falling back to tiktok_sample video...")
        
        // Fallback to tiktok_sample
        if let asset = NSDataAsset(name: "tiktok_sample") {
            print("✅ Found tiktok_sample data asset as fallback")
            let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("tiktok_sample.mov")
            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)
                print("✅ Created temp file for fallback at: \(tempURL)")
                return tempURL
            } catch {
                print("❌ Failed to write tiktok_sample fallback: \(error)")
            }
        }
        
        return nil
    }
}

#Preview {
    FullscreenPlayerView(
        isPresented: .constant(true),
        track: Track(
            title: "Wobbly Wiggly (Remix)",
            genres: ["Drum n Bass", "Electronic", "Indie"],
            artworkName: "wobbly_wiggly",
            badge: "Video"
        )
    )
}