//
//  ConfirmationView.swift
//  lichunWebsocket
//
//  Confirmation screen before starting the game
//

import SwiftUI

struct ConfirmationView: View {
    @EnvironmentObject var webSocketService: WebSocketService

    var name: String
    var age: Int
    var sex: String
    @State private var loading = false

    // Animation states
    @State private var isLoaded = false
    @State private var celebrationScale = false
    @State private var sparkleRotation: Double = 0

    var body: some View {
        ZStack {
            // Warm gradient background
            LinearGradient(
                colors: [
                    AppColors.background,
                    AppColors.background.lighter(by: 0.05)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .edgesIgnoringSafeArea(.all)

            ScrollView {
                VStack(spacing: AppSpacing.xl) {
                    Spacer()
                        .frame(height: AppSpacing.xl)

                    // Celebration icon
                    ZStack {
                        // Sparkle background effects
                        ForEach(0..<8) { index in
                            Image(systemName: "sparkle")
                                .font(.system(size: 20))
                                .foregroundColor(AppColors.accent.opacity(0.6))
                                .offset(
                                    x: cos(Double(index) * .pi / 4) * 60,
                                    y: sin(Double(index) * .pi / 4) * 60
                                )
                                .rotationEffect(.degrees(sparkleRotation + Double(index * 45)))
                                .opacity(isLoaded ? 1 : 0)
                                .scaleEffect(celebrationScale ? 1.2 : 0.8)
                        }

                        // Main success icon
                        Image(systemName: "checkmark.seal.fill")
                            .font(.system(size: 80))
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [AppColors.primary, AppColors.accent],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .shadow(color: AppColors.primary.opacity(0.5), radius: 20, x: 0, y: 8)
                            .scaleEffect(isLoaded ? 1 : 0.3)
                            .rotationEffect(.degrees(isLoaded ? 0 : -180))
                    }
                    .frame(height: 150)

                    // Success message
                    VStack(spacing: AppSpacing.sm) {
                        Text("All Set!")
                            .font(.system(size: 40, weight: .bold, design: .rounded))
                            .foregroundStyle(
                                LinearGradient(
                                    colors: [AppColors.primary, AppColors.accent],
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                            .opacity(isLoaded ? 1 : 0)
                            .offset(y: isLoaded ? 0 : -20)

                        Text("Your adventure is about to begin")
                            .font(.appBody)
                            .foregroundColor(AppColors.secondaryText)
                            .multilineTextAlignment(.center)
                            .opacity(isLoaded ? 1 : 0)
                    }

                    // Character summary card
                    BaseCard(
                        backgroundColor: AppColors.surfaceElevated,
                        enableAnimation: true
                    ) {
                        VStack(spacing: AppSpacing.md) {
                            Text("Your Character")
                                .appCaptionStyle()
                                .textCase(.uppercase)
                                .kerning(1)

                            // Character details
                            VStack(spacing: AppSpacing.sm) {
                                InfoRow(
                                    icon: "person.fill",
                                    label: "Name",
                                    value: name,
                                    gradient: true
                                )

                                InfoRow(
                                    icon: "calendar",
                                    label: "Age",
                                    value: "\(age) years",
                                    gradient: false
                                )

                                InfoRow(
                                    icon: sex == "Male" ? "figure.stand" : "figure.stand.dress",
                                    label: "Gender",
                                    value: sex,
                                    gradient: false
                                )
                            }
                        }
                    }
                    .opacity(isLoaded ? 1 : 0)
                    .offset(y: isLoaded ? 0 : 20)
                    .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.3), value: isLoaded)

                    // Encouraging message card
                    BaseCard(
                        backgroundColor: AppColors.primary.opacity(0.15),
                        borderColor: AppColors.primary.opacity(0.3)
                    ) {
                        HStack(spacing: AppSpacing.md) {
                            Image(systemName: "lightbulb.fill")
                                .font(.system(size: 24))
                                .foregroundStyle(
                                    LinearGradient(
                                        colors: [AppColors.primary, AppColors.accent],
                                        startPoint: .top,
                                        endPoint: .bottom
                                    )
                                )

                            Text("Every choice you make will shape your character's unique journey. Have fun!")
                                .font(.appCaption)
                                .foregroundColor(AppColors.primaryText)
                                .lineSpacing(3)
                        }
                    }
                    .opacity(isLoaded ? 1 : 0)
                    .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.4), value: isLoaded)

                    // Start button
                    PrimaryButton(
                        title: loading ? "Preparing Your World..." : "Start Your Journey!",
                        action: {
                            loading = true
                            sendDataToServer()
                        },
                        isLoading: loading
                    )
                    .opacity(isLoaded ? 1 : 0)
                    .scaleEffect(isLoaded ? 1 : 0.9)
                    .animation(.spring(response: 0.6, dampingFraction: 0.75).delay(0.5), value: isLoaded)

                    Spacer()
                        .frame(height: AppSpacing.xl)
                }
                .padding(.horizontal, AppSpacing.xl)
            }
        }
        .onAppear {
            // Entrance animation
            withAnimation(.spring(response: 0.8, dampingFraction: 0.65)) {
                isLoaded = true
            }

            // Celebration pulse
            withAnimation(
                .easeInOut(duration: 2.0)
                .repeatForever(autoreverses: true)
            ) {
                celebrationScale = true
            }

            // Sparkle rotation
            withAnimation(
                .linear(duration: 20.0)
                .repeatForever(autoreverses: false)
            ) {
                sparkleRotation = 360
            }

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

            // Register the current APNs token for the newly-created character.
            webSocketService.registerSavedDeviceTokenIfNeeded(force: true)
        }
    }

    private func sendDataToServer() {
        hapticFeedback()
        let data: [String: Any] = [
            "name": name,
            "age": age,
            "sex": sex
        ]

        let message: [String: Any] = [
            "type": "characterSetup",
            "message": data
        ]
        webSocketService.sendMessage(message: message)
    }
}

// MARK: - Supporting Views

private struct InfoRow: View {
    let icon: String
    let label: String
    let value: String
    let gradient: Bool

    var body: some View {
        HStack(spacing: AppSpacing.md) {
            // Icon
            Image(systemName: icon)
                .font(.system(size: 20, weight: .semibold))
                .foregroundStyle(
                    gradient ?
                    LinearGradient(
                        colors: [AppColors.primary, AppColors.accent],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ) :
                    LinearGradient(
                        colors: [AppColors.secondaryText, AppColors.secondaryText],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
                .frame(width: 30)

            // Label
            Text(label)
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
                .frame(width: 70, alignment: .leading)

            Spacer()

            // Value
            Text(value)
                .font(.appBodyBold)
                .foregroundColor(AppColors.primaryText)
        }
        .padding(AppSpacing.sm)
        .background(AppColors.background.opacity(0.5))
        .cornerRadius(AppSpacing.cornerRadius)
    }
}

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