import Localization
import SwiftUI

// Add "Tap to Unmute" overlay that shows on top of Hooks
// tab on the first launch
public struct TapToUnmuteOverlay: View {
    let onTap: () -> Void

    @State private var pulseAnimations: [UUID] = []
    @State private var animationTask: Task<Void, Never>?

    private let centerSize: CGFloat = 88
    private let maxPulseRadius: CGFloat = 114
    private let animationDuration: Double = 1.0
    private let pulseInterval: Double = 2.0

    public init(onTap: @escaping () -> Void) {
        self.onTap = onTap
    }

    public var body: some View {
        Button(action: onTap) {
            VStack(spacing: 24) {
                tapToUnmuteTitle
                pulsingUnmuteButton
            }
            .padding(.bottom, 48)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .ignoresSafeArea()
            .contentShape(Rectangle())
        }
        .buttonStyle(PlainButtonStyle())
        .accessibilityLabel(L10n.FeatureHooks.tapToUnmute)
        .onAppear {
            startPulseAnimation()
        }
        .onDisappear {
            stopPulseAnimation()
        }
    }

    private var tapToUnmuteTitle: some View {
        Text(L10n.FeatureHooks.tapToUnmute)
            .typographyV1(.tapToUnmuteTitle)
            .foregroundColor(.white)
    }

    private var pulsingUnmuteButton: some View {
        ZStack {
            // Pulsing circles behind button
            ForEach(pulseAnimations, id: \.self) { _ in
                PulseCircle(
                    centerRadius: centerSize,
                    maxRadius: maxPulseRadius,
                    duration: animationDuration
                )
                .transition(.opacity)
            }
            .opacity(pulseAnimations.isEmpty ? 0 : 1)

            // Unmute button
            unmuteButton
        }
    }

    @ViewBuilder
    private var unmuteButton: some View {
        if #available(iOS 26.0, *) {
            Image.Icon.volumeMute
                .resizable()
                .frame(width: 40, height: 40)
                .foregroundColor(.white)
                .frame(width: centerSize, height: centerSize)
                .glassEffect(.regular.interactive())
        } else {
            ZStack {
                Circle()
                    .fill(.ultraThinMaterial)
                    .frame(width: centerSize, height: centerSize)
                Circle()
                    .fill(.clear)
                    .strokeBorder(Color.SemanticV2.backgroundGlassDense, lineWidth: 0.25, antialiased: true)
                    .frame(width: centerSize, height: centerSize)
                Image.Icon.volumeMute
                    .resizable()
                    .frame(width: 40, height: 40)
                    .foregroundColor(.white)
            }
            .frame(width: centerSize, height: centerSize)
            .clipShape(Circle())
        }
    }
}

private extension TapToUnmuteOverlay {
    private func startPulseAnimation() {
        animationTask = Task {
            // Initial delay after appearing
            try? await Task.sleep(for: .milliseconds(300))

            while !Task.isCancelled {
                addPulse()
                try? await Task.sleep(for: .seconds(pulseInterval))
            }
        }
    }

    private func stopPulseAnimation() {
        animationTask?.cancel()
        animationTask = nil
        pulseAnimations.removeAll()
    }

    @MainActor
    private func addPulse() {
        guard !Task.isCancelled else { return }

        // Add to array if we didn't dismiss the view
        let id = UUID()
        pulseAnimations.append(id)

        Task {
            try? await Task.sleep(for: .seconds(animationDuration))
            guard !Task.isCancelled else { return }

            await MainActor.run {
                pulseAnimations.removeAll { $0 == id }
            }
        }
    }
}

private struct PulseCircle: View {
    let centerRadius: CGFloat
    let maxRadius: CGFloat
    let duration: Double

    @State private var scale: CGFloat = 1.0
    @State private var opacity: Double = 0.2

    var body: some View {
        Circle()
            .fill(.ultraThinMaterial)
            .overlay(
                Circle()
                    .inset(by: 0.5)
                    .stroke(.white, lineWidth: 1)
            )
            .frame(width: centerRadius, height: centerRadius)
            .scaleEffect(scale)
            .opacity(opacity)
            .onAppear {
                withAnimation(.spring(duration: duration, bounce: 0.2)) {
                    scale = maxRadius / centerRadius
                }
                withAnimation(.easeInOut(duration: duration)) {
                    opacity = 0
                }
            }
    }
}

private extension TypographyV1 {
    static let tapToUnmuteTitle: TypographyV1 = .init(
        name: "Tap to Unmute",
        size: 18,
        style: .body,
        weight: .ppNeueMontrealMedium,
        kerning: 0.36,
        lineHeight: 18
    )
}
