import APIClient
import AVFoundation
import ComponentLibrary
import ComposableArchitecture
import FeatureClipDetail
import Foundation
import OmniPlayerClient
import PlayerClient
import StatsigClient
import SwiftUI

public struct ExpandedPlayerMediaBackground: View {
    let clip: Clip
    let hasPlayableScene: Bool
    let hasPlayableInputVideo: Bool

    @Shared(.inMemory(.playingClipKey)) var playingClip: Clip?
    @Shared(.inMemory(.isPlayingKey)) var isPlaying: Bool = false
    @Shared(.inMemory(.playingVideoCoverUrlKey)) var playingVideoCoverUrl: String = ""
    @Dependency(PlayerClient.self) var playerClient
    @Dependency(VideoCoverClient.self) var videoCoverClient

    var shouldShowVideoPlayer: Bool {
        guard let videoCoverUrl = clip.videoCoverUrl else {
            return false
        }
        let currentUrl = playingVideoCoverUrl
        let isCurrentClip = (clip.id == playingClip?.id)
        return (currentUrl == videoCoverUrl) && isCurrentClip
    }

    var isScenePlaying: Bool {
        guard let playingClip else { return false }
        return playingClip.id == clip.id && isPlaying
    }

    public var body: some View {
        ZStack {
            mediaBackgroundAsset
                .frame(width: UIScreen.width, height: UIScreen.height)
                .clipped()
        }
    }

    private var avPlayer: AVPlayer? {
        if hasPlayableScene {
            @Dependency(OmniPlayerClient.self) var playerClient
            return playerClient.getUnderlyingPlayer()
        } else {
            return nil
        }
    }

    // Either shows an image or, if this is a Short,
    // the looping input video if it's `Me` viewing
    @ViewBuilder
    public var mediaBackgroundAsset: some View {
        ZStack {
            if hasPlayableScene {
                ZStack {
                    RemoteImage(url: clip.largeImageUrl, fallbackId: clip.id.remoteId)
                        .opacity(!isScenePlaying ? .one : .zero)
                    VideoPreviewView(player: avPlayer)
                        .opacity(isScenePlaying ? .one : .zero)
                }
            } else if FeatureFlag.legacy.videoSongCover,
                      clip.videoCoverUrl != nil
            {
                RemoteImage(
                    url: clip.largeImageUrl,
                    fallbackId: clip.id.remoteId,
                    backgroundColor: Color.SemanticV1.alwaysBlack1,
                    contentMode: clip.isVideoLandscape ? .fit : .fill
                )
                if shouldShowVideoPlayer {
                    VideoCoverView(
                        player: videoCoverClient.getAVPlayer(),
                        resizeMode: clip.isVideoLandscape ? .resizeAspect : .resizeAspectFill
                    )
                }
            } else {
                RemoteImage(url: clip.largeImageUrl, fallbackId: clip.id.remoteId)
            }
        }
    }
}
