//
//  ProfileMenuView.swift
//  lichunWebsocket
//
//  Profile menu with card-based navigation to all player features
//  Replaces the "More" tab with a cleaner, more organized layout
//

import SwiftUI

struct ProfileMenuView: View {
    @EnvironmentObject var appViewModel: AppViewModel
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) var dismiss
    @ObservedObject private var liveActivityManager = LiveActivityManager.shared
    @State private var showDebugTools = false
    @State private var showSettings = false

    // Badge indicators
    private var hasDailyRewardAvailable: Bool {
        if let state = webSocketService.dailyRewardState {
            return state.canClaim && !state.todaysClaimed
        }
        return false
    }

    private var dailyQuestsClaimableCount: Int {
        if let state = webSocketService.dailyQuestsState {
            return state.quests.filter { $0.canClaim }.count
        }
        return 0
    }

    var body: some View {
        ScrollView(showsIndicators: false) {
            VStack(spacing: AppSpacing.md) {
                // Header section with character info
                VStack(spacing: AppSpacing.xs) {
                    Text(webSocketService.person.firstname)
                        .font(.appDisplayTitle)
                        .foregroundColor(AppColors.primaryText)

                    Text("Level \(webSocketService.person.ageYears)")
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                }
                .padding(.top, AppSpacing.xl)
                .padding(.bottom, AppSpacing.sm)

                    // Cards grid
                    LazyVGrid(columns: [
                        GridItem(.flexible(), spacing: AppSpacing.sm),
                        GridItem(.flexible(), spacing: AppSpacing.sm)
                    ], spacing: AppSpacing.sm) {

                        // Characters
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showRelationships = true
                            }
                        }) {
                            MenuCard(
                                icon: "person.2.fill",
                                title: "Characters",
                                color: AppColors.friend,
                                hasBadge: false
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Store
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showStore = true
                            }
                        }) {
                            MenuCard(
                                icon: "storefront.fill",
                                title: "Store",
                                color: AppColors.accent,
                                hasBadge: false
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Daily Rewards
                        Button(action: {
                            webSocketService.showDailyRewards = true
                        }) {
                            MenuCard(
                                icon: "calendar.badge.clock",
                                title: "Daily Rewards",
                                color: AppColors.happiness,
                                hasBadge: hasDailyRewardAvailable,
                                subtitle: dailyRewardSubtitle
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Daily Quests
                        Button(action: {
                            webSocketService.showDailyQuests = true
                        }) {
                            MenuCard(
                                icon: "checklist",
                                title: "Daily Quests",
                                color: AppColors.intelligence,
                                hasBadge: dailyQuestsClaimableCount > 0,
                                subtitle: dailyQuestsSubtitle
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Achievements
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showAchievements = true
                            }
                        }) {
                            MenuCard(
                                icon: "trophy.fill",
                                title: "Achievements",
                                color: AppColors.prestige,
                                hasBadge: false
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Items
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showItems = true
                            }
                        }) {
                            MenuCard(
                                icon: "shippingbox.fill",
                                title: "Items",
                                color: AppColors.money,
                                hasBadge: false
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Life Goals (Wave 2)
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showLifeGoals = true
                            }
                        }) {
                            MenuCard(
                                icon: "target",
                                title: "Life Goals",
                                color: AppColors.prestige,
                                hasBadge: false,
                                subtitle: lifeGoalsSubtitle
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Collection (Wave 2)
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showCollection = true
                            }
                        }) {
                            MenuCard(
                                icon: "square.grid.2x2.fill",
                                title: "Collection",
                                color: AppColors.intelligence,
                                hasBadge: false
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Prestige (Wave 2)
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showPrestige = true
                            }
                        }) {
                            MenuCard(
                                icon: "star.circle.fill",
                                title: "Prestige",
                                color: AppColors.family,
                                hasBadge: false,
                                subtitle: "\(webSocketService.person.prestige) prestige"
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Do an Activity (Wave 2: performActivity)
                        Button(action: {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                appViewModel.showPerformActivity = true
                            }
                        }) {
                            MenuCard(
                                icon: "bolt.heart.fill",
                                title: "Do an Activity",
                                color: AppColors.success,
                                hasBadge: false
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Time Skip
                        Button(action: {
                            dismiss()
                            webSocketService.showTimeSkipModal = true
                        }) {
                            MenuCard(
                                icon: "forward.fill",
                                title: "Time Skip",
                                color: AppColors.primary,
                                hasBadge: false
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Live Activity
                        Button(action: {
                            Task {
                                if liveActivityManager.isFollowing {
                                    await liveActivityManager.stopFollowing(webSocketService: webSocketService)
                                } else {
                                    await liveActivityManager.startFollowing(webSocketService: webSocketService)
                                }
                            }
                        }) {
                            MenuCard(
                                icon: "dot.radiowaves.left.and.right",
                                title: "Live Activity",
                                color: liveActivityManager.isFollowing ? AppColors.success : AppColors.secondary,
                                hasBadge: liveActivityManager.isFollowing,
                                subtitle: liveActivityManager.statusHint
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Settings & Privacy (data export + account deletion).
                        // Entry point for the App Store-required in-app account
                        // deletion path; badged when a deletion is scheduled.
                        Button(action: {
                            showSettings = true
                        }) {
                            MenuCard(
                                icon: "gearshape.fill",
                                title: "Settings & Privacy",
                                color: AppColors.secondary,
                                hasBadge: webSocketService.deletionScheduledAt != nil,
                                subtitle: webSocketService.deletionScheduledAt != nil
                                    ? "Deletion scheduled" : "Data & account"
                            )
                        }
                        .buttonStyle(PlainButtonStyle())

                        // Debug Tools
                        Button(action: {
                            showDebugTools = true
                        }) {
                            MenuCard(
                                icon: "wrench.and.screwdriver.fill",
                                title: "Debug Tools",
                                color: AppColors.secondary,
                                hasBadge: false,
                                subtitle: "Money, energy, diamonds"
                            )
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    .padding(.horizontal, AppSpacing.md)
                }

                Spacer(minLength: AppSpacing.xl)
            }
            .padding(.bottom, AppSpacing.xl)
            .background(AppColors.background)
            .sheet(isPresented: $showDebugTools) {
                DebugToolsView()
                    .environmentObject(webSocketService)
            }
            .sheet(isPresented: $showSettings) {
                SettingsView()
                    .environmentObject(webSocketService)
            }
            .overlay(alignment: .topTrailing) {
                Button(action: {
                    dismiss()
                }) {
                    ZStack {
                        Circle()
                            .fill(AppColors.surfaceElevated)
                            .frame(width: 36, height: 36)
                            .shadow(
                                color: Color.black.opacity(0.1),
                                radius: 4,
                                x: 0,
                                y: 2
                            )

                        Image(systemName: "xmark")
                            .font(.system(size: 14, weight: .semibold))
                            .foregroundColor(AppColors.secondaryText)
                    }
                }
                .padding(.top, AppSpacing.md)
                .padding(.trailing, AppSpacing.md)
            }
    }

    private var dailyRewardSubtitle: String? {
        if let state = webSocketService.dailyRewardState {
            if state.currentStreak > 0 {
                return "🔥 \(state.currentStreak) day streak"
            }
        }
        return nil
    }

    private var dailyQuestsSubtitle: String? {
        let count = dailyQuestsClaimableCount
        if count > 0 {
            return "🎁 \(count) ready"
        }
        return nil
    }

    private var lifeGoalsSubtitle: String? {
        if let goals = webSocketService.player.lifeGoals {
            return "\(goals.lifeScore) life score"
        }
        return nil
    }
}

// MARK: - Settings & Privacy Hub

/// Settings & Privacy hub. The in-app entry point to GDPR data export and
/// account deletion — both views previously existed but were never presented
/// anywhere, so the App Store-required in-app account-deletion path was
/// unreachable. Defined here (alongside ProfileMenuView, which presents it) so
/// it joins the build target without a project-file change.
struct SettingsView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.dismiss) var dismiss

    @State private var showDataExport = false
    @State private var showDeleteAccount = false

    var body: some View {
        NavigationView {
            List {
                // Surface a scheduled deletion at the top so the user always sees
                // (and can act on) a pending deletion from Settings.
                if webSocketService.deletionScheduledAt != nil {
                    Section {
                        Label(
                            "Your account is scheduled for deletion. Open Delete Account to cancel.",
                            systemImage: "exclamationmark.triangle.fill"
                        )
                        .foregroundColor(AppColors.warning)
                        .font(.appCaption)
                    }
                }

                Section(header: Text("Privacy & Data")) {
                    Button(action: { showDataExport = true }) {
                        Label("Export My Data", systemImage: "square.and.arrow.up")
                    }
                }

                Section(footer: Text("Permanently deletes your account and all associated data after a 30-day grace period. You can cancel anytime during the grace period.")) {
                    Button(role: .destructive, action: { showDeleteAccount = true }) {
                        Label("Delete Account", systemImage: "trash")
                    }
                }

                Section(footer: Text("BaoLife")) {
                    HStack {
                        Text("Version")
                        Spacer()
                        Text(appVersionString)
                            .foregroundColor(.secondary)
                    }
                }
            }
            .navigationTitle("Settings")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Done") { dismiss() }
                }
            }
            .sheet(isPresented: $showDataExport) {
                DataExportView()
                    .environmentObject(webSocketService)
            }
            .sheet(isPresented: $showDeleteAccount) {
                AccountDeletionView()
                    .environmentObject(webSocketService)
            }
        }
    }

    private var appVersionString: String {
        let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0"
        let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? ""
        return build.isEmpty ? version : "\(version) (\(build))"
    }
}

// MARK: - Menu Card Component

struct MenuCard: View {
    let icon: String
    let title: String
    let color: Color
    let hasBadge: Bool
    let subtitle: String?

    init(
        icon: String,
        title: String,
        color: Color,
        hasBadge: Bool,
        subtitle: String? = nil
    ) {
        self.icon = icon
        self.title = title
        self.color = color
        self.hasBadge = hasBadge
        self.subtitle = subtitle
    }

    var body: some View {
        BaseCard(
            backgroundColor: AppColors.surfaceElevated,
            showShadow: true
        ) {
            VStack(spacing: AppSpacing.sm) {
                ZStack {
                    // Icon background
                    Circle()
                        .fill(color.opacity(0.15))
                        .frame(width: 56, height: 56)

                    Image(systemName: icon)
                        .font(.system(size: 26))
                        .foregroundColor(color)

                    // Badge indicator
                    if hasBadge {
                        Circle()
                            .fill(AppColors.error)
                            .frame(width: 10, height: 10)
                            .overlay(
                                Circle()
                                    .strokeBorder(AppColors.surfaceElevated, lineWidth: 2)
                            )
                            .offset(x: 20, y: -20)
                    }
                }

                VStack(spacing: 2) {
                    Text(title)
                        .font(.appBodyBold)
                        .foregroundColor(AppColors.primaryText)
                        .multilineTextAlignment(.center)

                    if let subtitle = subtitle {
                        Text(subtitle)
                            .font(.appCaption)
                            .foregroundColor(AppColors.secondaryText)
                            .lineLimit(1)
                    }
                }
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, AppSpacing.xs)
        }
        .frame(height: 120)
    }
}

// MARK: - Preview

#if DEBUG
struct ProfileMenuView_Previews: PreviewProvider {
    static var previews: some View {
//        ProfileMenuView()
//            .environmentObject(WebSocketService())
//            .environmentObject(AppViewModel())
    }
}
#endif
