import AnalyticsClient
import AVFoundation
import ComponentLibrary
import ComposableArchitecture
import FeatureClipDetail
import SwiftUI

struct CompactPlayerPlayPauseButtonV2: View {
    private enum Constants {
        static let buttonSize: CGFloat = 48
        static let iconSize: CGFloat = 24
        static let playIconPadding: CGFloat = 2 // Used to visually center the play icon
    }

    let playTapped: () -> Void
    let pauseTapped: () -> Void
    let timeControlStatus: AVPlayer.TimeControlStatus

    @Dependency(AnalyticsClient.self) var analyticsClient

    @State var transparency = 0.0

    public var body: some View {
        let isPlaying = timeControlStatus == .playing
        Button {
            switch timeControlStatus {
            case .paused:
                playTapped()
            case .waitingToPlayAtSpecifiedRate:
                pauseTapped()
            case .playing:
                pauseTapped()
            @unknown default:
                break
            }
            transparency = 0.4
            Task { @MainActor in
                try? await Task.sleep(for: .seconds(0.1))
                transparency = 0.0
            }
        } label: {
            ZStack {
                Circle()
                    .fill(.ultraThinMaterial)
                    .frame(width: 48, height: 48)
                    .opacity(transparency)
                    .environment(\.colorScheme, .light)
                    .animation(.easeInOut(duration: 0.1), value: transparency)

                if timeControlStatus != .waitingToPlayAtSpecifiedRate {
                    Image.Omniplayer.play
                        .resizable()
                        .frame(width: Constants.iconSize, height: Constants.iconSize)
                        .foregroundColor(.SemanticV2.foregroundPrimary)
                        .scaleEffect(isPlaying ? 0 : 1)
                        .opacity(isPlaying ? 0 : 1)
                        .padding(.trailing, Constants.playIconPadding)
                        .offset(x: 1.5)

                    Image.Omniplayer.pause
                        .resizable()
                        .frame(width: Constants.iconSize, height: Constants.iconSize)
                        .foregroundColor(.SemanticV2.foregroundPrimary)
                        .scaleEffect(isPlaying ? 1 : 0)
                        .opacity(isPlaying ? 1 : 0)
                } else {
                    Image.Omniplayer.pause
                        .resizable()
                        .frame(width: Constants.iconSize, height: Constants.iconSize)
                        .foregroundColor(.SemanticV2.foregroundPrimary)
                }
            }
            .frame(width: 48, height: 48)
            .contentShape(Circle())
        }
        .foregroundColor(.primary)
        .buttonStyle(ScaleButtonStyle(scaleAmount: 0.98))
    }
}
