//
//  AchievementUnlockModal.swift
//  lichunWebsocket
//
//  Celebration modal shown when achievements are unlocked
//

import SwiftUI

struct AchievementUnlockModal: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) var dismiss
    @State private var currentIndex = 0
    @State private var showConfetti = true
    @State private var scale: CGFloat = 0.5
    @State private var rotation: Double = -15
    @State private var sparkleOpacity: Double = 0
    @State private var cardOffset: CGFloat = 500
    @State private var pulseScale: CGFloat = 1.0

    var achievements: [Achievement] {
        webSocketService.unacknowledgedAchievements
    }

    var currentAchievement: Achievement? {
        guard currentIndex < achievements.count else { return nil }
        return achievements[currentIndex]
    }

    var body: some View {
        ZStack {
            // Background overlay
            AppColors.modalOverlay
                .ignoresSafeArea()
                .onTapGesture {
                    // Prevent dismissal by tapping background
                }

            // Confetti animation
            if showConfetti {
                AchievementConfettiView()
            }

            // Achievement Card
            if let achievement = currentAchievement {
                VStack(spacing: AppSpacing.lg) {
                    Spacer()

                    VStack(spacing: AppSpacing.lg) {
                        // Celebration emoji with warm stars
                        HStack(spacing: 12) {
                            Text("⭐")
                                .font(.system(size: 50))
                                .scaleEffect(scale)
                            Text("🏆")
                                .font(.system(size: 60))
                                .scaleEffect(scale)
                            Text("⭐")
                                .font(.system(size: 50))
                                .scaleEffect(scale)
                        }
                        .onAppear {
                            withAnimation(.spring(response: 0.6, dampingFraction: 0.6)) {
                                scale = 1.0
                            }
                        }

                        Text("Achievement Unlocked!")
                            .font(.system(size: 28, weight: .bold, design: .rounded))
                            .foregroundColor(.white)
                            .shadow(color: Color.black.opacity(0.2), radius: 4, x: 0, y: 2)

                        // Achievement Icon with animation
                        ZStack {
                            // Pulsing outer ring
                            Circle()
                                .stroke(achievement.category.color.opacity(0.3), lineWidth: 3)
                                .frame(width: 120, height: 120)
                                .scaleEffect(pulseScale)

                            Circle()
                                .fill(achievement.category.color.opacity(0.3))
                                .frame(width: 100, height: 100)

                            Image(systemName: "trophy.fill")
                                .font(.system(size: 50))
                                .foregroundColor(achievement.category.color)

                            // Sparkles around trophy
                            ForEach(0..<8) { index in
                                Image(systemName: "sparkle")
                                    .font(.system(size: 12))
                                    .foregroundColor(.yellow)
                                    .opacity(sparkleOpacity)
                                    .offset(
                                        x: cos(Double(index) * .pi / 4) * 60,
                                        y: sin(Double(index) * .pi / 4) * 60
                                    )
                                    .rotationEffect(.degrees(Double(index) * 45))
                            }
                        }
                        .scaleEffect(scale)
                        .rotationEffect(.degrees(rotation))
                        .onAppear {
                            withAnimation(.spring(response: 0.6, dampingFraction: 0.6).delay(0.1)) {
                                scale = 1.0
                                rotation = 0
                            }

                            // Sparkle animation
                            withAnimation(
                                .easeInOut(duration: 0.8)
                                .repeatForever(autoreverses: true)
                                .delay(0.3)
                            ) {
                                sparkleOpacity = 1.0
                            }

                            // Pulse ring animation
                            withAnimation(
                                .easeInOut(duration: 1.5)
                                .repeatForever(autoreverses: true)
                                .delay(0.2)
                            ) {
                                pulseScale = 1.2
                            }
                        }

                        // Name
                        Text(achievement.name)
                            .font(.appLargeTitle)
                            .fontWeight(.semibold)
                            .foregroundColor(.white)
                            .multilineTextAlignment(.center)
                            .padding(.horizontal, AppSpacing.md)

                        // Description
                        Text(achievement.description)
                            .font(.appBody)
                            .foregroundColor(.white.opacity(0.9))
                            .multilineTextAlignment(.center)
                            .padding(.horizontal, AppSpacing.lg)

                        // Reward Badge with warm golden styling
                        HStack(spacing: AppSpacing.sm) {
                            Image(systemName: "star.fill")
                                .font(.system(size: 20))
                                .foregroundColor(Color(red: 1.0, green: 0.84, blue: 0.0))
                            Text("You earned")
                                .font(.appBody)
                                .foregroundColor(.white.opacity(0.9))
                            Text("\(achievement.reward)")
                                .font(.system(size: 28, weight: .bold, design: .rounded))
                                .foregroundColor(Color(red: 1.0, green: 0.84, blue: 0.0))
                            Image(systemName: "gem.fill")
                                .font(.system(size: 22))
                                .foregroundColor(Color(red: 1.0, green: 0.84, blue: 0.0))
                        }
                        .padding(.horizontal, AppSpacing.lg)
                        .padding(.vertical, AppSpacing.md)
                        .background(
                            LinearGradient(
                                colors: [
                                    Color.white.opacity(0.25),
                                    Color.white.opacity(0.15)
                                ],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .cornerRadius(AppSpacing.cornerRadius)
                        .overlay(
                            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                                .stroke(Color.white.opacity(0.4), lineWidth: 1.5)
                        )
                        .shadow(color: Color.black.opacity(0.15), radius: 8, x: 0, y: 4)
                    }
                    .padding(AppSpacing.xl)
                    .background(
                        LinearGradient(
                            gradient: Gradient(colors: [
                                achievement.category.color.opacity(0.9),
                                achievement.category.color.opacity(0.7)
                            ]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .cornerRadius(AppSpacing.largeCornerRadius)
                    .shadow(
                        color: Color.black.opacity(0.3),
                        radius: 20,
                        x: 0,
                        y: 10
                    )
                    .padding(.horizontal, AppSpacing.xl)
                    .offset(y: cardOffset)
                    .onAppear {
                        // Card bounce-in animation
                        withAnimation(.spring(response: 0.7, dampingFraction: 0.6)) {
                            cardOffset = 0
                        }

                        // Haptic feedback
                        let generator = UINotificationFeedbackGenerator()
                        generator.notificationOccurred(.success)
                    }

                    Spacer()

                    // Continue Button
                    Button(action: acknowledgeAndContinue) {
                        Text(currentIndex < achievements.count - 1 ? "Next" : "Awesome!")
                            .font(.appHeadline)
                            .foregroundColor(AppColors.primaryText)
                            .frame(maxWidth: .infinity)
                            .padding(AppSpacing.md)
                            .background(AppColors.surfaceElevated)
                            .cornerRadius(AppSpacing.cornerRadius)
                            .shadow(
                                color: Color.black.opacity(0.2),
                                radius: 8,
                                x: 0,
                                y: 4
                            )
                    }
                    .padding(.horizontal, AppSpacing.xl)
                    .padding(.bottom, AppSpacing.xl)
                }
            }
        }
        .onAppear {
            // Play sound
            SoundManager.shared.playSound(.achievement)

            // Start confetti animation
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                withAnimation {
                    showConfetti = false
                }
            }
        }
    }

    private func acknowledgeAndContinue() {
        if let achievement = currentAchievement {
            webSocketService.acknowledgeAchievement(achievement.id)
        }

        if currentIndex < achievements.count - 1 {
            // Reset animations for next achievement
            currentIndex += 1
            scale = 0.5
            rotation = -15
            showConfetti = true
            sparkleOpacity = 0
            cardOffset = 500
            pulseScale = 1.0

            SoundManager.shared.playSound(.achievement)

            // Trigger haptic
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.success)

            withAnimation(.spring(response: 0.7, dampingFraction: 0.6)) {
                cardOffset = 0
                scale = 1.0
                rotation = 0
            }

            withAnimation(
                .easeInOut(duration: 0.8)
                .repeatForever(autoreverses: true)
                .delay(0.3)
            ) {
                sparkleOpacity = 1.0
            }

            withAnimation(
                .easeInOut(duration: 1.5)
                .repeatForever(autoreverses: true)
                .delay(0.2)
            ) {
                pulseScale = 1.2
            }

            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                withAnimation {
                    showConfetti = false
                }
            }
        } else {
            webSocketService.unacknowledgedAchievements.removeAll()
            dismiss()
        }
    }
}

// MARK: - Confetti Animation

struct AchievementConfettiView: View {
    @State private var animate = false

    var body: some View {
        ZStack {
            ForEach(0..<50) { index in
                ConfettiPiece(delay: Double.random(in: 0...0.5))
            }
        }
        .onAppear {
            animate = true
        }
    }
}

struct ConfettiPiece: View {
    let delay: Double
    @State private var yOffset: CGFloat = -100
    @State private var xOffset: CGFloat = 0
    @State private var rotation: Double = 0
    @State private var opacity: Double = 1

    // Warm celebratory colors - gold, bronze, warm yellows, oranges
    private let colors: [Color] = [
        Color(red: 1.0, green: 0.84, blue: 0.0),      // Gold
        Color(red: 1.0, green: 0.65, blue: 0.0),      // Orange-gold
        Color(red: 0.85, green: 0.65, blue: 0.13),    // Bronze
        Color(red: 1.0, green: 0.92, blue: 0.23),     // Bright yellow
        Color(red: 1.0, green: 0.5, blue: 0.0),       // Warm orange
        Color(red: 0.8, green: 0.5, blue: 0.2),       // Copper
        Color(red: 1.0, green: 0.75, blue: 0.0),      // Amber
        Color(red: 0.98, green: 0.8, blue: 0.4)       // Light gold
    ]

    var body: some View {
        RoundedRectangle(cornerRadius: 3)
            .fill(colors.randomElement() ?? AppColors.primary)
            .frame(width: 10, height: 10)
            .rotationEffect(.degrees(rotation))
            .opacity(opacity)
            .offset(
                x: xOffset,
                y: yOffset
            )
            .onAppear {
                let randomX = CGFloat.random(in: -150...150)
                let screenHeight = UIScreen.main.bounds.height

                withAnimation(
                    Animation
                        .linear(duration: Double.random(in: 2...4))
                        .delay(delay)
                ) {
                    yOffset = screenHeight + 100
                    xOffset = randomX
                    rotation = Double.random(in: 0...720)
                    opacity = 0
                }
            }
    }
}

// MARK: - Preview
// Preview removed - requires backend connection
