import ComponentLibrary
import ComposableArchitecture
import SwiftUI

public struct BlendedToolbarButtonView: View {
    private let image: Image
    private let color: Color
    private let backgroundColor: Color
    private let action: () -> Void

    public init(
        image: Image,
        color: Color = Color.SemanticV1.iconPrimary,
        backgroundColor: Color = Color.SemanticV2.backgroundGlassThick,
        action: @escaping () -> Void
    ) {
        self.image = image
        self.color = color
        self.backgroundColor = backgroundColor
        self.action = action
    }

    public var body: some View {
        Button {
            UIImpactFeedbackGenerator(style: .light).impactOccurred()
            action()
        } label: {
            ZStack(alignment: .center) {
                backgroundColor
                    .background(BackdropBlurView(radius: 50))
                    .clipShape(.circle)

                image
                    .resizable()
                    .foregroundColor(color)
                    .frame(maxWidth: 24, maxHeight: 24)
            }
            .frame(minWidth: 42, minHeight: 42)
            .clipShape(Rectangle())
        }
        .buttonStyle(.plain)
    }
}

struct BlurView: UIViewRepresentable {
    var style: UIBlurEffect.Style

    func makeUIView(context _: Context) -> UIVisualEffectView {
        let blurEffect = UIBlurEffect(style: style)
        let blurView = UIVisualEffectView(effect: blurEffect)
        return blurView
    }

    func updateUIView(_ uiView: UIVisualEffectView, context _: Context) {
        uiView.effect = UIBlurEffect(style: style)
    }
}

// A UIViewRepresentable that uses UIVisualEffectView with only blur, no vibrancy
struct BackdropBlurView: UIViewRepresentable {
    var radius: CGFloat

    func makeUIView(context _: Context) -> UIVisualEffectView {
        // Create a blur effect without any vibrancy or color shifting
        let view = UIVisualEffectView(effect: UIBlurEffect(style: .regular))

        // Remove the default subtle overlay tint that UIVisualEffectView adds
        view.backgroundColor = .clear

        // Disable vibrancy effect that might alter colors
        view.contentView.backgroundColor = .clear

        return view
    }

    func updateUIView(_ uiView: UIVisualEffectView, context _: Context) {
        // You can dynamically update the blur radius by adjusting alpha
        // (Unfortunately UIBlurEffect doesn't let you set radius directly)
        uiView.alpha = min(1.0, radius * 0.0333)
    }
}

struct ColorPreservingBlurView: UIViewRepresentable {
    var blurRadius: CGFloat

    func makeUIView(context _: Context) -> UIView {
        // Create a container view
        let container = UIView(frame: .zero)
        container.backgroundColor = .clear

        // Create a specialized blur effect view
        let blurView = CustomIntensityVisualEffectView(effect: UIBlurEffect(style: .light))
        blurView.translatesAutoresizingMaskIntoConstraints = false

        container.addSubview(blurView)

        // Make blur view fill the container
        NSLayoutConstraint.activate([
            blurView.topAnchor.constraint(equalTo: container.topAnchor),
            blurView.leadingAnchor.constraint(equalTo: container.leadingAnchor),
            blurView.trailingAnchor.constraint(equalTo: container.trailingAnchor),
            blurView.bottomAnchor.constraint(equalTo: container.bottomAnchor),
        ])

        return container
    }

    func updateUIView(_ uiView: UIView, context _: Context) {
        guard let blurView = uiView.subviews.first as? CustomIntensityVisualEffectView else { return }
        blurView.intensity = blurRadius * 0.0333 // Scale to useful range
    }

    // Custom class that allows adjusting blur intensity without color shifts
    class CustomIntensityVisualEffectView: UIVisualEffectView {
        private var animator: UIViewPropertyAnimator?

        var intensity: CGFloat = 0 {
            didSet {
                animator?.fractionComplete = intensity
            }
        }

        override init(effect: UIVisualEffect?) {
            super.init(effect: nil)

            // Create animator to control blur intensity
            animator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [weak self] in
                self?.effect = effect
            }
            animator?.pausesOnCompletion = true
            animator?.fractionComplete = intensity
        }

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

        deinit {
            animator?.stopAnimation(true)
        }
    }
}
