//
//  DeepLinkManager.swift
//  lichunWebsocket
//
//  Handles deep linking for testing and navigation
//  Usage: xcrun simctl openurl booted "baolife://screen/path"
//

import SwiftUI

/// Deep link routes supported by the app
enum DeepLinkRoute: Equatable {
    // Main tabs
    case home
    case activities
    case social(segment: SocialSegment?)
    case more

    // Modals
    case store
    case achievements
    case characters
    case dailyRewards
    case dailyQuests
    case items
    case timeSkip

    // Testing helpers
    case skipOnboarding
    case setAge(Int)

    // Debug commands
    case debugDump
    case debugPreset(TestPreset)

    enum SocialSegment: String {
        case dating
        case messages
    }

    enum TestPreset: String {
        case teen           // 15-year-old in high school
        case youngAdult     // 22-year-old with job
        case adult          // 35-year-old with family
        case wealthy        // High money/diamonds
        case lowEnergy      // Low energy for testing refills
        case relationships  // Character with multiple relationships
    }
}

/// Manages deep link URL parsing and navigation
class DeepLinkManager: ObservableObject {
    static let shared = DeepLinkManager()

    @Published var pendingRoute: DeepLinkRoute?

    private init() {}

    /// Parse a URL into a DeepLinkRoute
    /// Supports: baolife://route/subroute?param=value
    func parse(url: URL) -> DeepLinkRoute? {
        guard url.scheme == "baolife" else { return nil }

        let host = url.host ?? ""
        let pathComponents = url.pathComponents.filter { $0 != "/" }
        let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []

        switch host {
        // Main tabs
        case "home":
            return .home
        case "activities":
            return .activities
        case "social":
            if let segment = pathComponents.first {
                return .social(segment: DeepLinkRoute.SocialSegment(rawValue: segment))
            }
            return .social(segment: nil)
        case "more":
            return .more

        // Modals
        case "store":
            return .store
        case "achievements":
            return .achievements
        case "characters", "relationships":
            return .characters
        case "daily-rewards":
            return .dailyRewards
        case "daily-quests":
            return .dailyQuests
        case "items":
            return .items
        case "time-skip":
            return .timeSkip

        // Testing helpers
        case "skip-onboarding":
            return .skipOnboarding
        case "set-age":
            if let ageString = queryItems.first(where: { $0.name == "age" })?.value,
               let age = Int(ageString) {
                return .setAge(age)
            }
            return nil

        // Debug commands
        case "debug":
            if let subcommand = pathComponents.first {
                switch subcommand {
                case "dump":
                    return .debugDump
                case "preset":
                    if let presetName = pathComponents.dropFirst().first,
                       let preset = DeepLinkRoute.TestPreset(rawValue: presetName) {
                        return .debugPreset(preset)
                    }
                    // Also check query param: baolife://debug/preset?name=teen
                    if let presetName = queryItems.first(where: { $0.name == "name" })?.value,
                       let preset = DeepLinkRoute.TestPreset(rawValue: presetName) {
                        return .debugPreset(preset)
                    }
                    print("[DeepLink] Unknown preset. Available: teen, youngAdult, adult, wealthy, lowEnergy, relationships")
                    return nil
                default:
                    print("[DeepLink] Unknown debug command: \(subcommand)")
                    return nil
                }
            }
            return nil

        default:
            print("[DeepLink] Unknown route: \(host)")
            return nil
        }
    }

    /// Handle a deep link route by updating app state
    func handle(route: DeepLinkRoute, appViewModel: AppViewModel, webSocketService: WebSocketService? = nil) {
        // Check if this is a debug preset route
        var isPresetRoute = false
        if case .debugPreset = route { isPresetRoute = true }

        // Debug routes that don't require onboarding
        let isDebugRoute = route == .skipOnboarding || route == .debugDump || isPresetRoute

        // Ensure we're past onboarding for most routes
        let requiresOnboarding = !isDebugRoute

        if requiresOnboarding && !appViewModel.onboardingComplete {
            print("[DeepLink] Skipping route - onboarding not complete")
            return
        }

        switch route {
        // Main tabs (0: Home, 1: Activities, 2: Social, 3: More)
        case .home:
            appViewModel.selectedTab = 0

        case .activities:
            appViewModel.selectedTab = 1

        case .social(let segment):
            appViewModel.selectedTab = 2
            switch segment {
            case .dating:
                appViewModel.selectedSocialSegment = 0
            case .messages:
                appViewModel.selectedSocialSegment = 1
            case .none:
                break
            }

        case .more:
            appViewModel.selectedTab = 3
            appViewModel.showQuickActions = true

        // Modals
        case .store:
            appViewModel.showStore = true

        case .achievements:
            appViewModel.showAchievements = true

        case .characters:
            appViewModel.showRelationships = true

        case .dailyRewards:
            appViewModel.showProfileMenu = true
            // Daily rewards would need additional handling

        case .dailyQuests:
            appViewModel.showProfileMenu = true
            // Daily quests would need additional handling

        case .items:
            appViewModel.showItems = true

        case .timeSkip:
            appViewModel.showProfileMenu = true
            // Time skip would need additional handling

        // Testing helpers
        case .skipOnboarding:
            appViewModel.onboardingComplete = true
            UserDefaults.standard.set(true, forKey: "onboardingComplete")
            print("[DeepLink] Onboarding skipped")

        case .setAge(let age):
            // This would need WebSocketService integration to actually set the age
            print("[DeepLink] Set age requested: \(age)")

        // Debug commands
        case .debugDump:
            dumpGameState(webSocketService: webSocketService)

        case .debugPreset(let preset):
            applyTestPreset(preset, webSocketService: webSocketService)
        }

        print("[DeepLink] Handled route: \(route)")
    }

    // MARK: - Debug Helpers

    /// Dump current game state to console for debugging
    private func dumpGameState(webSocketService: WebSocketService?) {
        guard let ws = webSocketService else {
            print("[DeepLink] ⚠️ WebSocketService not available for state dump")
            ToastManager.shared.showError("WebSocketService not available")
            return
        }

        // Show toast confirmation
        ToastManager.shared.showSuccess("State dumped to console")

        print("""
        ═══════════════════════════════════════════════════════════════
        🎮 GAME STATE DUMP
        ═══════════════════════════════════════════════════════════════

        📡 CONNECTION
        ─────────────
        Connected: \(ws.isConnected)
        App Loaded: \(ws.appLoaded)

        👤 CHARACTER
        ─────────────
        Name: \(ws.person.firstname) \(ws.person.lastname)
        Age: \(ws.person.ageYears) years
        Sex: \(ws.person.sex)
        Status: \(ws.person.status)

        📊 STATS
        ─────────────
        Energy: \(ws.person.calcEnergy)/\(ws.person.peakEnergy)
        Health: \(ws.person.health)
        Happiness: \(ws.person.happiness)
        Intelligence: \(ws.person.intelligence)
        Mood: \(ws.person.mood)

        💰 RESOURCES
        ─────────────
        Money: $\(ws.person.money)
        Diamonds: \(ws.person.diamonds)
        Prestige: \(ws.person.prestige)

        ⏰ TIME
        ─────────────
        Date: \(ws.player.date)
        Time: \(ws.player.hourOfDay):\(String(format: "%02d", ws.player.minuteOfHour))
        Game Speed: \(ws.player.gameSpeed)

        👥 RELATIONSHIPS
        ─────────────
        Total: \(ws.player.r.count)
        \(ws.player.r.prefix(5).map { "  - \($0.firstname) \($0.lastname) (affinity: \($0.affinity))" }.joined(separator: "\n"))
        \(ws.player.r.count > 5 ? "  ... and \(ws.player.r.count - 5) more" : "")

        📚 ACTIVITIES
        ─────────────
        Current: \(ws.person.activities.count)
        \(ws.person.activities.prefix(5).map { "  - \($0)" }.joined(separator: "\n"))

        🏆 ACHIEVEMENTS
        ─────────────
        Unlocked: \(ws.achievements.filter { $0.unlocked }.count)/\(ws.achievements.count)

        📋 EVENTS
        ─────────────
        Life Events: \(ws.lifeEvents.count)
        Unclaimed: \(ws.unclaimedEventCount)
        Question Queue: \(ws.questionQueue.count)

        🎓 TUTORIAL
        ─────────────
        Step: \(ws.tutorialStep)
        Complete: \(ws.tutorialComplete)

        ═══════════════════════════════════════════════════════════════
        """)
    }

    /// Apply a test preset by sending a debug command to server
    private func applyTestPreset(_ preset: DeepLinkRoute.TestPreset, webSocketService: WebSocketService?) {
        guard let ws = webSocketService else {
            print("[DeepLink] ⚠️ WebSocketService not available for test preset")
            ToastManager.shared.showError("WebSocketService not available")
            return
        }

        // Show toast confirmation
        ToastManager.shared.showInfo("Preset '\(preset.rawValue)' requested")

        print("[DeepLink] 🧪 Applying test preset: \(preset.rawValue)")

        // Send debug setup message to server
        ws.sendMessage(message: WebSocketCommands.debugSetup(preset: preset.rawValue))

        print("""
        [DeepLink] 📤 Sent debugSetup request for preset: \(preset.rawValue)

        Available presets:
          • teen         - 15yo high school student
          • youngAdult   - 22yo with job
          • adult        - 35yo with family
          • wealthy      - High money/diamonds
          • lowEnergy    - Low energy (test refills)
          • relationships - Multiple relationships

        ⚠️  Server must support 'debugSetup' message type.
            If preset doesn't apply, check server implementation.
        """)
    }
}

// MARK: - URL Scheme Documentation
/*
 Supported Deep Links:

 MAIN TABS:
 - baolife://home              → Home tab
 - baolife://activities        → Activities tab
 - baolife://social            → Social tab (Dating)
 - baolife://social/dating     → Social tab, Dating segment
 - baolife://social/messages   → Social tab, Messages segment
 - baolife://more              → Quick Actions menu

 MODALS:
 - baolife://store             → Store modal
 - baolife://achievements      → Achievements modal
 - baolife://characters        → Characters/Relationships modal
 - baolife://relationships     → Characters/Relationships modal (alias)
 - baolife://daily-rewards     → Daily Rewards modal
 - baolife://daily-quests      → Daily Quests modal
 - baolife://items             → Items modal
 - baolife://time-skip         → Time Skip modal

 TESTING:
 - baolife://skip-onboarding   → Skip onboarding flow
 - baolife://set-age?age=5     → Set character age (requires server support)

 USAGE (Terminal):
 xcrun simctl openurl booted "baolife://social/dating"
 xcrun simctl openurl booted "baolife://skip-onboarding"
 */
