import SwiftUI
import AVKit

struct VideoPlayerView: UIViewControllerRepresentable {
    let streamURL: URL

    func makeUIViewController(context: Context) -> AVPlayerViewController {
        let controller = AVPlayerViewController()

        print("🎬 Creating player for URL: \(streamURL)")

        // Create AVAsset with URL for more robust loading
        let asset = AVURLAsset(url: streamURL)
        let playerItem = AVPlayerItem(asset: asset)

        // Store player item in coordinator to maintain reference
        context.coordinator.playerItem = playerItem

        // Create player with player item
        let player = AVPlayer(playerItem: playerItem)

        // Store player in coordinator to maintain strong reference
        context.coordinator.player = player

        controller.player = player
        controller.showsPlaybackControls = true

        // Observe player status
        player.addObserver(context.coordinator, forKeyPath: "status", options: [.new], context: nil)
        playerItem.addObserver(context.coordinator, forKeyPath: "status", options: [.new], context: nil)

        // Delay play slightly to ensure player is ready
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            print("▶️ Starting playback")
            player.play()
        }

        return controller
    }

    func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
        // No updates needed
    }

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

    class Coordinator: NSObject {
        var player: AVPlayer?
        var playerItem: AVPlayerItem?

        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == "status" {
                if let player = object as? AVPlayer {
                    print("🎵 Player status: \(player.status.rawValue)")
                    if player.status == .failed {
                        print("❌ Player failed: \(player.error?.localizedDescription ?? "unknown error")")
                    }
                } else if let item = object as? AVPlayerItem {
                    print("📹 Player item status: \(item.status.rawValue)")
                    if item.status == .failed {
                        print("❌ Player item failed: \(item.error?.localizedDescription ?? "unknown error")")
                        if let error = item.error as? NSError {
                            print("   Error code: \(error.code), domain: \(error.domain)")
                            print("   Error details: \(error.userInfo)")
                        }
                    } else if item.status == .readyToPlay {
                        print("✅ Player item ready to play")
                    }
                }
            }
        }

        deinit {
            player?.removeObserver(self, forKeyPath: "status")
            playerItem?.removeObserver(self, forKeyPath: "status")
        }
    }
}
