//
//  DebugToolsView.swift
//  lichunWebsocket
//
//  Developer tools for granting money, energy, and diamonds (server-authoritative).
//

import SwiftUI

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

    @State private var customAmount: String = "100"
    @State private var customResource: DebugResource = .money
    @State private var presetsExpanded = false

    private enum DebugResource: String, CaseIterable, Identifiable {
        case money
        case energy
        case diamonds

        var id: String { rawValue }

        var title: String {
            switch self {
            case .money: return "Money"
            case .energy: return "Energy"
            case .diamonds: return "Diamonds"
            }
        }
    }

    var body: some View {
        NavigationView {
            ScrollView(showsIndicators: false) {
                VStack(spacing: AppSpacing.md) {
                    resourceSummaryCard
                    energySection
                    moneySection
                    diamondsSection
                    customGrantSection
                    presetsSection
                }
                .padding(AppSpacing.md)
            }
            .background(AppColors.background)
            .navigationTitle("Debug Tools")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Done") { dismiss() }
                }
            }
        }
    }

    private var resourceSummaryCard: some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated) {
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                Text("Current resources")
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                HStack(spacing: AppSpacing.sm) {
                    summaryPill(
                        label: "Energy",
                        value: "\(webSocketService.person.energy)",
                        color: AppColors.energy
                    )
                    summaryPill(
                        label: "Money",
                        value: "$\(webSocketService.person.money)",
                        color: AppColors.money
                    )
                    summaryPill(
                        label: "Diamonds",
                        value: "\(webSocketService.person.diamonds)",
                        color: AppColors.diamond
                    )
                }
            }
        }
    }

    private func summaryPill(label: String, value: String, color: Color) -> some View {
        VStack(spacing: 4) {
            Text(label)
                .font(.appCaption)
                .foregroundColor(AppColors.secondaryText)
            Text(value)
                .font(.appBodyBold)
                .foregroundColor(color)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, AppSpacing.xs)
        .background(color.opacity(0.12))
        .clipShape(RoundedRectangle(cornerRadius: AppSpacing.cornerRadius))
    }

    private var energySection: some View {
        grantSection(title: "Energy", color: AppColors.energy) {
            grantButton("+25", energy: 25)
            grantButton("+50", energy: 50)
            grantButton("Fill", energy: 100, mode: "set")
        }
    }

    private var moneySection: some View {
        grantSection(title: "Money", color: AppColors.money) {
            grantButton("+$500", money: 500)
            grantButton("+$5,000", money: 5000)
        }
    }

    private var diamondsSection: some View {
        grantSection(title: "Diamonds", color: AppColors.diamond) {
            grantButton("+10", diamonds: 10)
            grantButton("+100", diamonds: 100)
        }
    }

    private var customGrantSection: some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated) {
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                Text("Custom grant")
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                Picker("Resource", selection: $customResource) {
                    ForEach(DebugResource.allCases) { resource in
                        Text(resource.title).tag(resource)
                    }
                }
                .pickerStyle(.segmented)

                TextField("Amount", text: $customAmount)
                    .keyboardType(.numberPad)
                    .textFieldStyle(.roundedBorder)

                Button(action: applyCustomGrant) {
                    Text("Apply")
                        .font(.appBodyBold)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, AppSpacing.sm)
                }
                .buttonStyle(.borderedProminent)
                .tint(AppColors.primary)
            }
        }
    }

    private var presetsSection: some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated) {
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                Button(action: { presetsExpanded.toggle() }) {
                    HStack {
                        Text("Life presets")
                            .font(.appHeadline)
                            .foregroundColor(AppColors.primaryText)
                        Spacer()
                        Image(systemName: presetsExpanded ? "chevron.up" : "chevron.down")
                            .foregroundColor(AppColors.secondaryText)
                    }
                }
                .buttonStyle(.plain)

                if presetsExpanded {
                    presetButton("Teen", preset: "teen")
                    presetButton("Young adult", preset: "youngAdult")
                    presetButton("Adult", preset: "adult")
                    presetButton("Wealthy", preset: "wealthy")
                    presetButton("Low energy", preset: "lowEnergy")
                    presetButton("Relationships", preset: "relationships")
                }
            }
        }
    }

    private func grantSection<Content: View>(
        title: String,
        color: Color,
        @ViewBuilder actions: () -> Content
    ) -> some View {
        BaseCard(backgroundColor: AppColors.surfaceElevated) {
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                Text(title)
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                HStack(spacing: AppSpacing.sm) {
                    actions()
                }
            }
        }
    }

    private func grantButton(
        _ title: String,
        money: Int? = nil,
        energy: Int? = nil,
        diamonds: Int? = nil,
        mode: String = "add"
    ) -> some View {
        Button(title) {
            sendGrant(money: money, energy: energy, diamonds: diamonds, mode: mode)
        }
        .font(.appBodyBold)
        .frame(maxWidth: .infinity)
        .padding(.vertical, AppSpacing.sm)
        .background(AppColors.primary.opacity(0.12))
        .foregroundColor(AppColors.primaryText)
        .clipShape(RoundedRectangle(cornerRadius: AppSpacing.cornerRadius))
    }

    private func presetButton(_ title: String, preset: String) -> some View {
        Button(title) {
            webSocketService.sendMessage(message: WebSocketCommands.debugSetup(preset: preset))
            ToastManager.shared.showInfo("Preset '\(preset)' requested")
        }
        .font(.appBody)
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(.vertical, AppSpacing.xs)
    }

    private func applyCustomGrant() {
        guard let amount = Int(customAmount.trimmingCharacters(in: .whitespaces)), amount > 0 else {
            ToastManager.shared.showError("Enter a positive amount")
            return
        }

        switch customResource {
        case .money:
            sendGrant(money: amount)
        case .energy:
            sendGrant(energy: min(amount, 100))
        case .diamonds:
            sendGrant(diamonds: min(amount, 10_000))
        }
    }

    private func sendGrant(
        money: Int? = nil,
        energy: Int? = nil,
        diamonds: Int? = nil,
        mode: String = "add"
    ) {
        webSocketService.sendMessage(
            message: WebSocketCommands.debugGrant(
                money: money,
                energy: energy,
                diamonds: diamonds,
                mode: mode
            )
        )
    }
}
