import APIClient
import ComponentLibrary
import ComposableArchitecture
import Localization
import StatsigClient
import SwiftUI
import Utilities

public struct ExpandedPlayerClipDetails: View {
    @Bindable var store: StoreOf<ExpandedPlayerReducer>
    @Binding var verticalScrollPosition: CGFloat

    private let fadeStartThreshold: CGFloat = 0
    private let fadeEndThreshold: CGFloat = 50

    public init(store: StoreOf<ExpandedPlayerReducer>, verticalScrollPosition: Binding<CGFloat>) {
        self.store = store
        self._verticalScrollPosition = verticalScrollPosition
    }

    private var contentOpacity: Double {
        let fadeRange = fadeEndThreshold - fadeStartThreshold
        let scrollInFadeRange = max(0, verticalScrollPosition - fadeStartThreshold)
        return min(1.0, scrollInFadeRange / fadeRange)
    }

    public var body: some View {
        VStack(spacing: 12) {
            artistDetailsCard
            if !store.clip.tags.isEmpty || !(store.clip.negativeTags?.isEmpty ?? true) {
                styleDescriptionCard
            }

            if !store.clip.prompt.isEmpty {
                lyricsCard
            }

            createdAtCard
        }
        .opacity(contentOpacity)
    }

    @ViewBuilder
    private var artistDetailsCard: some View {
        ClipDetailsArtistDetailsView(avatarImageUrl: store.clip.avatarImageUrl,
                                     artistName: store.clip.displayName,
                                     artistFollowerCount: store.profile?.stats.followersCount.formatted(.number.notation(.compactName)) ?? "0",
                                     artistSongCount: store.profile?.stats.songs.formatted(.number.notation(.compactName)) ?? "0",
                                     authorTapped: {
                                         store.send(.authorTapped(handle: store.clip.handle))
                                     },
                                     followTapped: {
                                         store.send(.followTapped(handle: store.clip.handle, unfollow: store.profile?.isFollowing))
                                     },
                                     isFollowing: store.profile?.isFollowing ?? false,
                                     isCurrentUser: store.me.user.id == store.clip.userId,
                                     topClips: store.profile?.clips ?? [],
                                     playTopClipTapped: { clips, index in
                                         store.send(.playTopClipsAtIndex(clips, index))
                                     },
                                     isPlaying: store.isPlaying,
                                     playingClipId: store.playingClip?.id)
    }

    @ViewBuilder
    private var styleDescriptionCard: some View {
        ClipDetailsExpandedCardView(
            cardTitle: L10n.FeatureOmniPlayer.styleSectionTitle,
            subtitleText: store.clip.displayTags?.capitalized,
            bodyText: store.clip.tags.capitalized,
            negativeTags: store.clip.negativeTags,
            weirdnessConstraint: store.clip.weirdnessConstraint,
            styleWeight: store.clip.styleWeight,
            textColor: Color.SemanticV2.foregroundPrimary,
            backgroundColor: Color.SemanticV2.backgroundFogThin,
            buttonText: L10n.FeatureClipDetail.reuseStyle,
            buttonColor: Color.SemanticV2.backgroundFogThin,
            shouldShowButton: store.canRemix,
            onCopy: { store.send(.setToast(.success(L10n.FeatureOmniPlayer.stylesCopySuccessMessage))) },
            onButtonTap: {
                store.send(.reuseClipMetadata(.styles))
            }
        )
    }

    @ViewBuilder
    private var createdAtCard: some View {
        HStack(spacing: 10) {
            createdAt
            versioningPill
        }
        .frame(maxWidth: .infinity, alignment: .center)
        .padding(16)
        .glassBackground(shape: .rect(cornerRadius: 16), fallbackStyle: Color.SemanticV2.backgroundFogThin)
    }

    @ViewBuilder
    private var createdAt: some View {
        let date: String = store.clip.createdAt.map { DateFormatter.format($0) } ?? ""

        Text(L10n.FeatureOmniPlayer.createdText + " " + date)
            .typographyV1(.playerCardBody.neueMontrealRegular())
            .foregroundColor(.SemanticV2.foregroundPrimary)
    }

    @ViewBuilder
    private var versioningPill: some View {
        // Use ModelBadgeStyle if feature flag is enabled and style is available
        if FeatureFlag.legacy.v5LaunchModelStyles,
           let modelBadgeStyle = store.clip.modelBadgeStyle
        {
            Pill(type: .modelBadge(style: modelBadgeStyle))
        } else {
            // Fallback to default versioning pills
            switch store.clip.highLevelModel {
            case .previousToV4:
                EmptyView()

            case .v5:
                Pill(type: .versioning(version: .v5))

            case .v4:
                Pill(type: .versioning(version: .v4))

            case .v4_5:
                Pill(type: .versioning(version: .v4_5))

            case .v4_5Plus:
                Pill(type: .versioning(version: .v4_5Plus))
            }
        }
    }

    @ViewBuilder
    private var lyricsCard: some View {
        ClipDetailsSimpleCardView(
            cardTitle: L10n.FeatureOmniPlayer.lyricsSectionTitle,
            bodyText: store.clip.prompt,
            textColor: Color.SemanticV2.foregroundPrimary,
            backgroundColor: Color.SemanticV2.backgroundFogThin,
            buttonText: L10n.FeatureClipDetail.reuseLyrics,
            buttonColor: Color.SemanticV2.backgroundFogThin,
            shouldShowButton: store.canRemix,
            onCopy: { store.send(.setToast(.success(L10n.FeatureOmniPlayer.lyricsCopySuccessMessage))) },
            onButtonTap: {
                store.send(.reuseClipMetadata(.lyrics))
            }
        )
    }
}
