import UIKit

enum MobileMainControllerState {
    case pause
    case play
    case replay
}

final class MobileMainControllerButton: UIControl {
    private let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .systemUltraThinMaterialDark))
    private let imageView = UIImageView()

    var controllerState: MobileMainControllerState = .play {
        didSet {
            applyState()
        }
    }

    override var isHighlighted: Bool {
        didSet {
            alpha = isHighlighted ? 0.72 : 1.0
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        configureView()
        applyState()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        configureView()
        applyState()
    }

    override var intrinsicContentSize: CGSize {
        CGSize(width: 98, height: 98)
    }

    private func configureView() {
        backgroundColor = .clear
        accessibilityTraits = [.button]

        blurView.translatesAutoresizingMaskIntoConstraints = false
        blurView.isUserInteractionEnabled = false
        blurView.clipsToBounds = true
        addSubview(blurView)

        imageView.contentMode = .scaleAspectFit
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.isUserInteractionEnabled = false
        addSubview(imageView)

        NSLayoutConstraint.activate([
            blurView.leadingAnchor.constraint(equalTo: leadingAnchor),
            blurView.trailingAnchor.constraint(equalTo: trailingAnchor),
            blurView.topAnchor.constraint(equalTo: topAnchor),
            blurView.bottomAnchor.constraint(equalTo: bottomAnchor),

            imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: trailingAnchor),
            imageView.topAnchor.constraint(equalTo: topAnchor),
            imageView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        blurView.layer.cornerRadius = min(bounds.width, bounds.height) / 2
    }

    private func applyState() {
        switch controllerState {
        case .pause:
            imageView.image = UIImage(named: "player_button_pause")
            accessibilityLabel = "Pause"
        case .play:
            imageView.image = UIImage(named: "player_button_play")
            accessibilityLabel = "Play"
        case .replay:
            imageView.image = UIImage(named: "player_button_replay")
            accessibilityLabel = "Replay"
        }
    }
}
