import SwiftUI
import TVVLCKit

struct VLCVideoPlayerView: UIViewRepresentable {
    let vodItem: VODItem
    let startPosition: TimeInterval?
    let onProgressUpdate: ((TimeInterval, TimeInterval) -> Void)?
    @Environment(\.dismiss) private var dismiss

    init(vodItem: VODItem, startPosition: TimeInterval? = nil, onProgressUpdate: ((TimeInterval, TimeInterval) -> Void)? = nil) {
        self.vodItem = vodItem
        self.startPosition = startPosition
        self.onProgressUpdate = onProgressUpdate
    }

    func makeUIView(context: Context) -> UIView {
        // Create container view
        // Note: clipsToBounds helps prevent _UIReplicantView warnings during tab transitions
        let containerView = UIView()
        containerView.backgroundColor = .black
        containerView.clipsToBounds = true

        // Create player view on main thread
        let playerView = VLCPlayerView()
        playerView.translatesAutoresizingMaskIntoConstraints = false

        // Store player view in coordinator
        context.coordinator.playerView = playerView
        context.coordinator.containerView = containerView
        context.coordinator.startPosition = startPosition
        context.coordinator.hasSeekStartPosition = false

        // Add player view to container
        containerView.addSubview(playerView)

        // Create loading indicator
        let activityIndicator = UIActivityIndicatorView(style: .large)
        activityIndicator.color = .white
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        activityIndicator.startAnimating()
        containerView.addSubview(activityIndicator)

        context.coordinator.activityIndicator = activityIndicator

        // Setup constraints
        NSLayoutConstraint.activate([
            playerView.topAnchor.constraint(equalTo: containerView.topAnchor),
            playerView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
            playerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            playerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),

            activityIndicator.centerXAnchor.constraint(equalTo: containerView.centerXAnchor),
            activityIndicator.centerYAnchor.constraint(equalTo: containerView.centerYAnchor)
        ])

        // Set state change callback
        let coordinator = context.coordinator
        playerView.onStateChange = { [weak activityIndicator, weak coordinator] state in
            DispatchQueue.main.async {
                guard let coordinator = coordinator else { return }

                switch state {
                case .playing:
                    // Mark that we've started playing (spinner won't show for rebuffering)
                    coordinator.hasStartedPlaying = true
                    activityIndicator?.stopAnimating()
                    activityIndicator?.isHidden = true
                    // Seek to start position on first play
                    if let startPos = coordinator.startPosition,
                       !coordinator.hasSeekStartPosition {
                        coordinator.hasSeekStartPosition = true
                        coordinator.playerView?.seekTo(position: startPos)
                    }
                case .buffering, .opening:
                    // Only show spinner if we haven't started playing yet (initial load)
                    if !coordinator.hasStartedPlaying {
                        activityIndicator?.startAnimating()
                        activityIndicator?.isHidden = false
                    }
                case .error, .stopped, .ended:
                    activityIndicator?.stopAnimating()
                    activityIndicator?.isHidden = true
                default:
                    break
                }
            }
        }

        // Set progress update callback
        playerView.onProgressUpdate = onProgressUpdate

        // Load and play media
        if let url = vodItem.streamURLObject {
            playerView.loadMedia(from: url)
            playerView.play()
        }

        return containerView
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        // No updates needed
    }

    static func dismantleUIView(_ uiView: UIView, coordinator: Coordinator) {
        // Stop playback immediately when view is removed
        print("🎥 VLCVideoPlayerView dismantling - stopping playback")
        coordinator.playerView?.stop()
        coordinator.activityIndicator?.stopAnimating()
    }

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

    class Coordinator {
        var playerView: VLCPlayerView?
        var containerView: UIView?
        var activityIndicator: UIActivityIndicatorView?
        var startPosition: TimeInterval?
        var hasSeekStartPosition: Bool = false
        var hasStartedPlaying: Bool = false  // Track if we've started playing at least once
    }
}
