//
//  MainCharacterView.swift
//  lichunWebsocket
//
//  Main character display card showing avatar, stats, and resources with cozy styling
//

import SwiftUI

struct MainCharacterView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @EnvironmentObject var storeManager: StoreManager
    @State private var amount = 0
    private var money: Int { webSocketService.person.money }
    @State private var showShake = false
    @State private var isExpanded = false
    @State private var showProductListView = false
    @State private var showingPopup = false

    var body: some View {
        BaseCard(
            backgroundColor: AppColors.surfaceElevated,
            borderColor: AppColors.primary.opacity(0.15),
            showShadow: true,
            enableAnimation: true
        ) {
            VStack(spacing: AppSpacing.md) {
                // Character Header
                HStack(alignment: .top, spacing: AppSpacing.md) {
                    // Left: Character Info
                    VStack(alignment: .leading, spacing: AppSpacing.sm) {
                        // Name
                        Text("\(webSocketService.person.firstname) \(webSocketService.person.lastname)")
                            .font(.appTitle)
                            .foregroundColor(AppColors.primaryText)

                        // Age and Birthday
                        HStack(spacing: AppSpacing.xs) {
                            Text("\(webSocketService.person.ageYears) yrs")
                                .font(.appBody)
                                .foregroundColor(AppColors.secondaryText)
                            Text("•")
                                .foregroundColor(AppColors.disabledText)
                            Text(webSocketService.person.birthday)
                                .font(.appBody)
                                .foregroundColor(AppColors.secondaryText)
                        }

                        // Health Bar
                        CozyStatBar(
                            label: "Health",
                            value: Int(webSocketService.person.health * 100),
                            color: AppColors.health,
                            showPercentage: true,
                            height: 14
                        )
                        .frame(height: 40)

                        // Happiness Bar
                        CozyStatBar(
                            label: "Happiness",
                            value: webSocketService.person.happiness,
                            color: AppColors.happiness,
                            showPercentage: true,
                            height: 14
                        )
                        .frame(height: 40)
                    }

                    Spacer()

                    // Right: Avatar and Mood
                    VStack(spacing: AppSpacing.sm) {
                        CharacterAvatar(
                            imageURL: webSocketService.person.image,
                            name: webSocketService.person.firstname,
                            size: 120,
                            showBorder: true,
                            showGlow: true
                        )

                        Text(webSocketService.person.mood)
                            .font(.system(size: 13, weight: .medium, design: .rounded))
                            .foregroundColor(AppColors.secondaryText)
                    }
                }

                Divider()
                    .background(AppColors.disabledText.opacity(0.3))

                // Resources Section
                VStack(spacing: AppSpacing.sm) {
                    // Row 1: Energy and Diamonds
                    HStack(spacing: AppSpacing.md) {
                        // Energy
                        HStack(spacing: AppSpacing.xs) {
                            Image(systemName: "bolt.fill")
                                .foregroundColor(AppColors.energy)
                                .font(.system(size: 16))
                            Text("\(webSocketService.person.calcEnergy)")
                                .font(.appBodyBold)
                                .foregroundColor(AppColors.primaryText)
                            Text("Energy")
                                .font(.appCaption)
                                .foregroundColor(AppColors.secondaryText)
                        }
                        .padding(.horizontal, AppSpacing.sm)
                        .padding(.vertical, AppSpacing.xs)
                        .background(AppColors.energy.opacity(0.1))
                        .cornerRadius(AppSpacing.smallCornerRadius)

                        Spacer()

                        // Diamonds with shop button
                        HStack(spacing: AppSpacing.xs) {
                            Image(systemName: "gem.fill")
                                .foregroundColor(AppColors.diamond)
                                .font(.system(size: 16))
                            Text("\(webSocketService.person.diamonds)")
                                .font(.appBodyBold)
                                .foregroundColor(AppColors.primaryText)

                            Button(action: {
                                hapticFeedback(style: .light)
                                showProductListView = true
                            }) {
                                Image(systemName: "plus.circle.fill")
                                    .font(.system(size: 18))
                                    .foregroundColor(AppColors.primary)
                            }
                        }
                        .padding(.horizontal, AppSpacing.sm)
                        .padding(.vertical, AppSpacing.xs)
                        .background(AppColors.diamond.opacity(0.1))
                        .cornerRadius(AppSpacing.smallCornerRadius)
                        .sheet(isPresented: $showProductListView) {
                            NavigationView {
                                ProductGridView().environmentObject(storeManager)
                            }
                        }
                    }

                    // Row 2: Money and Prestige
                    HStack(spacing: AppSpacing.md) {
                        // Money with shake animation
                        HStack(spacing: AppSpacing.xs) {
                            Image(systemName: "dollarsign.circle.fill")
                                .foregroundColor(AppColors.money)
                                .font(.system(size: 16))
                            Text("\(money)")
                                .font(.appBodyBold)
                                .foregroundColor(AppColors.primaryText)
                                .modifier(Shake(animatableData: CGFloat(amount)))
                            Text("Money")
                                .font(.appCaption)
                                .foregroundColor(AppColors.secondaryText)
                        }
                        .padding(.horizontal, AppSpacing.sm)
                        .padding(.vertical, AppSpacing.xs)
                        .background(AppColors.money.opacity(0.1))
                        .cornerRadius(AppSpacing.smallCornerRadius)
                        .background(
                            ZStack {
                                if showShake {
                                    ConfettiView()
                                        .frame(width: 5, height: 5)
                                        .background(Color.clear)
                                        .offset(y: 0)
                                        .zIndex(-1)
                                        .onAppear {
                                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.50) {
                                                showShake = false
                                            }
                                        }
                                }
                            }
                        )

                        Spacer()

                        // Prestige
                        HStack(spacing: AppSpacing.xs) {
                            Image(systemName: "crown.fill")
                                .foregroundColor(AppColors.accent)
                                .font(.system(size: 16))
                            Text("\(webSocketService.person.prestige)")
                                .font(.appBodyBold)
                                .foregroundColor(AppColors.primaryText)
                            Text("Prestige")
                                .font(.appCaption)
                                .foregroundColor(AppColors.secondaryText)
                        }
                        .padding(.horizontal, AppSpacing.sm)
                        .padding(.vertical, AppSpacing.xs)
                        .background(AppColors.accent.opacity(0.1))
                        .cornerRadius(AppSpacing.smallCornerRadius)
                    }
                }
            }
        }
        .onChange(of: money) { newValue in
            showShake = true
            withAnimation(.spring(response: 0.3, dampingFraction: 0.6)) {
                amount += 1
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                withAnimation(.spring(response: 0.3, dampingFraction: 0.6)) {
                    amount = 0
                }
            }
        }
    }
}

// MARK: - Helper Functions

private func energyColor(_ energy: Int) -> Color {
    let normalizedEnergy = Double(energy + 25) / 125 // Normalize energy to range 0...1

    // Determine hue
    let hue: Double
    switch normalizedEnergy {
    case 0...0.33: // Lower part of energy range (from -25 to around 8)
        hue = 0 + normalizedEnergy * 3 * 0.17 // Interpolate from red to yellow
    case 0.33...1: // Upper part of energy range (from around 8 to 100)
        hue = 0.17 + (normalizedEnergy - 0.33) * 1.5 * 0.16 // Interpolate from yellow to green
    default:
        hue = 0.33 // Default to green
    }

    return Color(hue: hue, saturation: 1, brightness: 0.6)
}

// MARK: - Shake Animation

struct Shake: GeometryEffect {
    var amount: CGFloat = 10
    var shakesPerUnit = 3
    var animatableData: CGFloat

    func effectValue(size: CGSize) -> ProjectionTransform {
        ProjectionTransform(CGAffineTransform(translationX: amount * sin(animatableData * .pi * CGFloat(shakesPerUnit)), y: 0))
    }
}

extension AnyTransition {
    static var shake: AnyTransition {
        .modifier(active: Shake(animatableData: 1), identity: Shake(animatableData: 0))
    }
}

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