import Adamantium
import AnalyticsClient
import APIClient
import AVFoundation
import AVKit
import CommentsClient
import ComponentLibrary
import ComposableArchitecture
import EventBusClient
import FeatureClipDetail
import FeatureShare
import FeatureShareSheet
import FeatureToasts
import Localization
import PlayerClient
import StatsigClient
import SwiftUI
import Utilities

public class ClipBackgroundMediaCell: UICollectionViewCell {
    private var hostingController: UIHostingController<HostingView>?

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.backgroundColor = .clear
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override public func prepareForReuse() {
        super.prepareForReuse()
        hostingController?.view.removeFromSuperview()
        hostingController = nil
    }

    func configure(clip: Clip, hasPlayableScene: Bool, hasPlayableInputVideo: Bool) {
        hostingController?.view.removeFromSuperview()

        let hostingView = HostingView(
            clip: clip,
            hasPlayableScene: hasPlayableScene,
            hasPlayableInputVideo: hasPlayableInputVideo
        )

        hostingController = UIHostingController(rootView: hostingView)
        hostingController?.view.backgroundColor = .clear

        if let hostingView = hostingController?.view {
            hostingView.translatesAutoresizingMaskIntoConstraints = false
            contentView.addSubview(hostingView)
            NSLayoutConstraint.activate([
                hostingView.topAnchor.constraint(equalTo: contentView.topAnchor),
                hostingView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
                hostingView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
                hostingView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            ])
        }
    }

    struct HostingView: View {
        let clip: Clip
        let hasPlayableScene: Bool
        let hasPlayableInputVideo: Bool

        var body: some View {
            ZStack {
                Color.clear
                    .background(
                        ExpandedPlayerMediaBackground(
                            clip: clip,
                            hasPlayableScene: hasPlayableScene,
                            hasPlayableInputVideo: hasPlayableInputVideo
                        )
                    )
            }
            .ignoresSafeArea()
        }
    }
}
