//
//  EnergyRefillModal.swift
//  lichunWebsocket
//
//  Energy refill purchase modal with cozy UI design
//

import SwiftUI

struct EnergyRefillModal: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @EnvironmentObject var toastManager: ToastManager
    @Environment(\.dismiss) var dismiss
    @State private var selectedTier: EnergyRefillTier?
    @State private var showingConfirmation = false

    var body: some View {
        NavigationView {
            ZStack {
                // Cozy background
                AppColors.background.ignoresSafeArea()

                ScrollView {
                    VStack(spacing: AppSpacing.lg) {
                        // Header with icon and title - enhanced cozy design
                        VStack(spacing: AppSpacing.sm) {
                            ZStack {
                                Circle()
                                    .fill(
                                        LinearGradient(
                                            colors: [Color(red: 1.0, green: 0.8, blue: 0.4), Color(red: 1.0, green: 0.6, blue: 0.3)],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        )
                                    )
                                    .frame(width: 90, height: 90)
                                    .shadow(color: Color(red: 1.0, green: 0.7, blue: 0.3).opacity(0.4), radius: 12, x: 0, y: 6)

                                Image(systemName: "bolt.fill")
                                    .font(.system(size: 45))
                                    .foregroundColor(.white)
                            }

                            Text("Energy Refill")
                                .font(.appTitle)
                                .foregroundColor(AppColors.primaryText)

                            Text("Restore your energy to keep playing")
                                .font(.appBody)
                                .foregroundColor(AppColors.secondaryText)
                                .multilineTextAlignment(.center)
                        }
                        .padding(.top, AppSpacing.lg)

                        // Current Stats Card
                        HStack(spacing: AppSpacing.md) {
                            StatCard(
                                icon: "bolt.fill",
                                label: "Current",
                                value: "\(webSocketService.person.calcEnergy)",
                                color: AppColors.energy
                            )

                            StatCard(
                                icon: "gem.fill",
                                label: "Diamonds",
                                value: "\(webSocketService.person.diamonds)",
                                color: AppColors.diamond
                            )
                        }
                        .padding(.horizontal, AppSpacing.md)

                        // Unlimited Energy Status Banner
                        if let unlimitedUntil = webSocketService.unlimitedEnergyUntil,
                           unlimitedUntil > Date() {
                            UnlimitedEnergyBanner(expiresAt: unlimitedUntil)
                                .padding(.horizontal, AppSpacing.md)
                        }

                        // Refill Tiers
                        VStack(spacing: AppSpacing.md) {
                            ForEach(webSocketService.energyRefillTiers) { tier in
                                RefillTierCard(
                                    tier: tier,
                                    canAfford: webSocketService.person.diamonds >= tier.diamonds
                                ) {
                                    selectedTier = tier
                                    showingConfirmation = true
                                }
                            }
                        }
                        .padding(.horizontal, AppSpacing.md)
                        .padding(.bottom, AppSpacing.xl)
                    }
                }
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: { dismiss() }) {
                        Image(systemName: "xmark.circle.fill")
                            .font(.title3)
                            .foregroundColor(AppColors.secondaryText)
                    }
                }
            }
            .alert("Confirm Purchase", isPresented: $showingConfirmation) {
                Button("Cancel", role: .cancel) {
                    selectedTier = nil
                }
                Button("Purchase") {
                    if let tier = selectedTier {
                        purchaseTier(tier)
                    }
                }
            } message: {
                if let tier = selectedTier {
                    Text("Purchase \(tier.displayName) for \(tier.diamonds) diamonds?")
                }
            }
        }
        .onAppear {
            webSocketService.fetchEnergyRefillTiers()
            AnalyticsManager.shared.trackScreenView("energy_refill_modal", screenClass: "EnergyRefillModal")
        }
    }

    private func purchaseTier(_ tier: EnergyRefillTier) {
        // Check if player has enough diamonds
        guard webSocketService.person.diamonds >= tier.diamonds else {
            toastManager.show(.error, message: "Not enough diamonds!")
            SoundManager.shared.playSound(.error)
            selectedTier = nil
            return
        }

        webSocketService.purchaseEnergyRefill(tierType: tier.type)
        AnalyticsManager.shared.track(.purchaseInitiated(
            itemId: "energy_refill_\(tier.type)",
            itemName: tier.displayName,
            price: tier.diamonds
        ))
        selectedTier = nil
    }
}

// MARK: - Supporting Views

struct StatCard: View {
    let icon: String
    let label: String
    let value: String
    let color: Color

    var body: some View {
        VStack(spacing: AppSpacing.xs) {
            Image(systemName: icon)
                .font(.system(size: 24))
                .foregroundColor(color)

            Text(value)
                .font(.system(size: 22, weight: .bold, design: .rounded))
                .foregroundColor(AppColors.primaryText)

            Text(label)
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
        }
        .frame(maxWidth: .infinity)
        .padding(AppSpacing.md)
        .background(color.opacity(0.1))
        .cornerRadius(AppSpacing.cornerRadius)
        .overlay(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .stroke(color.opacity(0.3), lineWidth: 1)
        )
    }
}

struct UnlimitedEnergyBanner: View {
    let expiresAt: Date
    @State private var timeRemaining = ""
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        HStack(spacing: AppSpacing.sm) {
            Image(systemName: "infinity")
                .font(.system(size: 24))
                .foregroundColor(AppColors.energy)

            VStack(alignment: .leading, spacing: 2) {
                Text("Unlimited Energy Active")
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)
                Text("Expires in \(timeRemaining)")
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
            }

            Spacer()
        }
        .padding(AppSpacing.md)
        .background(AppColors.energy.opacity(0.15))
        .cornerRadius(AppSpacing.cornerRadius)
        .overlay(
            RoundedRectangle(cornerRadius: AppSpacing.cornerRadius)
                .stroke(AppColors.energy.opacity(0.3), lineWidth: 2)
        )
        .onReceive(timer) { _ in
            updateTimeRemaining()
        }
        .onAppear {
            updateTimeRemaining()
        }
    }

    private func updateTimeRemaining() {
        let remaining = expiresAt.timeIntervalSince(Date())
        if remaining > 0 {
            let hours = Int(remaining) / 3600
            let minutes = (Int(remaining) % 3600) / 60
            timeRemaining = "\(hours)h \(minutes)m"
        } else {
            timeRemaining = "Expired"
        }
    }
}

struct RefillTierCard: View {
    let tier: EnergyRefillTier
    let canAfford: Bool
    let onPurchase: () -> Void

    var body: some View {
        HStack(spacing: AppSpacing.md) {
            // Icon with premium gradient
            ZStack {
                Circle()
                    .fill(
                        LinearGradient(
                            colors: [Color(red: 1.0, green: 0.9, blue: 0.7).opacity(0.4), Color(red: 1.0, green: 0.8, blue: 0.5).opacity(0.4)],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: 60, height: 60)

                Image(systemName: tier.icon)
                    .font(.system(size: 28))
                    .foregroundColor(Color(red: 1.0, green: 0.7, blue: 0.3))
            }

            // Details
            VStack(alignment: .leading, spacing: 4) {
                Text(tier.displayName)
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                Text(tier.description)
                    .font(.appBody)
                    .foregroundColor(AppColors.secondaryText)
            }

            Spacer()

            // Price button with premium gradient
            Button(action: onPurchase) {
                HStack(spacing: 4) {
                    Text("\(tier.diamonds)")
                        .font(.system(size: 18, weight: .bold, design: .rounded))
                    Image(systemName: "gem.fill")
                        .font(.system(size: 14))
                }
                .foregroundColor(.white)
                .padding(.horizontal, AppSpacing.md)
                .padding(.vertical, AppSpacing.sm)
                .background(
                    canAfford ?
                    LinearGradient(
                        colors: [Color(red: 1.0, green: 0.8, blue: 0.4), Color(red: 1.0, green: 0.6, blue: 0.3)],
                        startPoint: .leading,
                        endPoint: .trailing
                    ) :
                    LinearGradient(
                        colors: [AppColors.disabledText, AppColors.disabledText],
                        startPoint: .leading,
                        endPoint: .trailing
                    )
                )
                .cornerRadius(AppSpacing.pillCornerRadius)
                .shadow(
                    color: canAfford ? Color(red: 1.0, green: 0.7, blue: 0.3).opacity(0.4) : Color.clear,
                    radius: 8,
                    x: 0,
                    y: 4
                )
            }
            .disabled(!canAfford)
        }
        .padding(AppSpacing.md)
        .background(AppColors.surfaceElevated)
        .cornerRadius(20)
        .overlay(
            RoundedRectangle(cornerRadius: 20)
                .stroke(
                    LinearGradient(
                        colors: [Color(red: 1.0, green: 0.9, blue: 0.7).opacity(0.3), Color(red: 1.0, green: 0.8, blue: 0.5).opacity(0.3)],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ),
                    lineWidth: 1
                )
        )
        .shadow(
            color: Color.black.opacity(0.06),
            radius: 10,
            x: 0,
            y: 4
        )
    }
}

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