//
//  PerformActivityView.swift
//  lichunWebsocket
//
//  Wave 2: proactive-agency UI. Lets the player choose a player-initiated
//  activity (study / exercise / socialize / side-hustle / hobby) and send the
//  `performActivity` command. Shows each activity's rough effect + energy cost,
//  gated optimistically on usable energy and minimum age (the server is
//  authoritative and replies with an error toast + refreshed playerObject).
//

import SwiftUI

struct PerformActivityView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) var dismiss

    // Gate activities on RAW energy, matching the server's energy gate
    // (performActivity.ts: `energy < energyCost`). Gating on calcEnergy here
    // falsely showed "Low energy" for every activity once a student's permanent
    // peakEnergy reserve dragged calcEnergy near 0, even with plenty of raw
    // energy the server would have accepted.
    private var usableEnergy: Int { webSocketService.person.energy }
    private var ageYears: Int { webSocketService.person.ageYears }

    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: AppSpacing.md) {
                    header

                    ForEach(PlayerActivityInfo.all) { activity in
                        PerformActivityRow(
                            activity: activity,
                            usableEnergy: usableEnergy,
                            ageYears: ageYears,
                            onPerform: { perform(activity) }
                        )
                    }
                    .padding(.horizontal, AppSpacing.md)

                    Text("Activities spend a free slot in your day and apply their effects right away.")
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                        .multilineTextAlignment(.center)
                        .padding(.horizontal, AppSpacing.lg)
                        .padding(.top, AppSpacing.sm)

                    Spacer(minLength: AppSpacing.xl)
                }
                .padding(.bottom, AppSpacing.xl)
            }
            .background(AppColors.background)
            .navigationTitle("Do an Activity")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: { dismiss() }) {
                        Image(systemName: "xmark.circle.fill")
                            .font(.title3)
                            .foregroundColor(AppColors.secondaryText)
                    }
                }
            }
            .onAppear {
                AnalyticsManager.shared.trackScreenView("perform_activity", screenClass: "PerformActivityView")
            }
        }
    }

    private var header: some View {
        VStack(spacing: AppSpacing.xs) {
            HStack(spacing: 6) {
                Image(systemName: "bolt.fill")
                    .font(.system(size: 14))
                    .foregroundColor(AppColors.energy)
                Text("\(usableEnergy) energy available")
                    .font(.appBodyBold)
                    .foregroundColor(AppColors.primaryText)
            }
            Text("Take charge of your day - pick something to do.")
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
        }
        .padding(.top, AppSpacing.md)
    }

    private func perform(_ activity: PlayerActivityInfo) {
        hapticFeedback(style: .medium)
        webSocketService.performActivity(activityId: activity.id)
        // Dismiss after sending; the server reply (toast + playerObject) updates
        // state. Keep the sheet open if you'd rather chain multiple — but a single
        // free slot is consumed per action, so closing avoids confusion.
        dismiss()
    }
}

// MARK: - Activity Row

private struct PerformActivityRow: View {
    let activity: PlayerActivityInfo
    let usableEnergy: Int
    let ageYears: Int
    let onPerform: () -> Void

    private var ageLocked: Bool { ageYears < activity.minAge }
    private var energyLocked: Bool { usableEnergy < activity.energyCost }
    private var disabled: Bool { ageLocked || energyLocked }

    var body: some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated, showShadow: true) {
            HStack(spacing: AppSpacing.md) {
                ZStack {
                    Circle()
                        .fill(activity.color.opacity(0.15))
                        .frame(width: 48, height: 48)
                    Image(systemName: activity.icon)
                        .font(.system(size: 22))
                        .foregroundColor(activity.color)
                }

                VStack(alignment: .leading, spacing: 2) {
                    Text(activity.title)
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.primaryText)
                    Text(activity.blurb)
                        .font(.appCaption)
                        .foregroundColor(AppColors.secondaryText)
                        .lineLimit(2)
                    HStack(spacing: 4) {
                        Image(systemName: "bolt.fill")
                            .font(.system(size: 10))
                            .foregroundColor(AppColors.energy)
                        Text("\(activity.energyCost) energy")
                            .font(.appCaption)
                            .foregroundColor(energyLocked ? AppColors.error : AppColors.secondaryText)
                    }
                }

                Spacer()

                Button(action: onPerform) {
                    Text(buttonLabel)
                        .font(.system(size: 14, weight: .semibold, design: .rounded))
                        .foregroundColor(.white)
                        .padding(.horizontal, AppSpacing.md)
                        .padding(.vertical, AppSpacing.sm)
                        .background(disabled ? AppColors.disabledText.opacity(0.4) : activity.color)
                        .cornerRadius(AppSpacing.pillCornerRadius)
                }
                .disabled(disabled)
            }
        }
        .opacity(disabled ? 0.7 : 1.0)
    }

    private var buttonLabel: String {
        if ageLocked { return "Age \(activity.minAge)+" }
        if energyLocked { return "Low energy" }
        return "Do it"
    }
}

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