//
//  INTEGRATION_EXAMPLES.swift
//  lichunWebsocket
//
//  Example integrations for Components 46-47: Loading States & Error Recovery
//  DO NOT ADD TO PROJECT - This is documentation only
//

import SwiftUI

// MARK: - Example 1: ContentView with Error Overlay
/*
struct ContentView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @EnvironmentObject var appViewModel: AppViewModel

    var body: some View {
        ZStack {
            // Your existing content
            TabView {
                HomeView()
                    .tabItem {
                        Label("Home", systemImage: "house.fill")
                    }

                ActivitiesView()
                    .tabItem {
                        Label("Activities", systemImage: "figure.run")
                    }

                // ... other tabs
            }
        }
        // Add error overlay - handles all errors globally
        .errorOverlay(error: $webSocketService.currentError) {
            // Retry action - reconnect to server
            webSocketService.reconnect()
        }
    }
}
*/

// MARK: - Example 2: List View with Skeleton Loading
/*
struct CharacterListView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @State private var isLoading = true

    var body: some View {
        VStack {
            Text("Characters")
                .font(.appLargeTitle)

            // LoadingStateView automatically shows skeletons while loading
            LoadingStateView(isLoading: isLoading, skeletonCount: 5) {
                ScrollView {
                    VStack(spacing: AppSpacing.md) {
                        ForEach(webSocketService.player.people) { person in
                            CharacterListCard(person: person)
                        }
                    }
                    .padding()
                }
            }
        }
        .onAppear {
            // Simulate loading
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                isLoading = false
            }
        }
    }
}
*/

// MARK: - Example 3: Character Creation with Progress
/*
struct CharacterCreationView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @State private var uploadProgress: Double = 0.0
    @State private var isUploading = false
    @State private var characterName = ""

    var body: some View {
        VStack(spacing: AppSpacing.lg) {
            TextField("Character Name", text: $characterName)
                .textFieldStyle(.roundedBorder)
                .padding()

            PrimaryButton(title: "Create Character") {
                createCharacter()
            }
            .disabled(characterName.isEmpty || isUploading)
        }
        // Show progress overlay while uploading
        .progressLoading(
            isUploading,
            message: "Creating character...",
            progress: $uploadProgress
        )
    }

    private func createCharacter() {
        isUploading = true
        uploadProgress = 0.0

        // Simulate upload progress
        Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
            uploadProgress += 0.1
            if uploadProgress >= 1.0 {
                timer.invalidate()
                isUploading = false

                // Send to server
                let message = [
                    "type": "createCharacter",
                    "name": characterName
                ]
                webSocketService.sendMessage(message: message)
            }
        }
    }
}
*/

// MARK: - Example 4: Messages View with Error Banner
/*
struct MessagesView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @State private var messageText = ""

    var body: some View {
        VStack {
            // Messages list
            ScrollView {
                ForEach(webSocketService.player.activeConversations) { conversation in
                    ConversationRow(conversation: conversation)
                }
            }

            // Message input
            HStack {
                TextField("Message...", text: $messageText)
                    .textFieldStyle(.roundedBorder)

                PrimaryButton(title: "Send") {
                    sendMessage()
                }
            }
            .padding()
        }
        // Show error banner at top (auto-dismisses after 3 seconds)
        .errorBanner(
            error: $webSocketService.currentError,
            autoDismiss: true,
            dismissDelay: 3.0
        )
    }

    private func sendMessage() {
        guard !messageText.isEmpty else { return }

        let message = [
            "type": "sendMessage",
            "message": messageText
        ]
        webSocketService.sendMessage(message: message)
        messageText = ""
    }
}
*/

// MARK: - Example 5: Activity View with Loading Overlay
/*
struct ActivityDetailView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    let activity: ActivityProtocol
    @State private var isLoading = false

    var body: some View {
        VStack(spacing: AppSpacing.lg) {
            Text(activity.name)
                .font(.appLargeTitle)

            Text(activity.description)
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)

            PrimaryButton(title: "Start Activity") {
                startActivity()
            }
        }
        .padding()
        // Simple loading overlay
        .loading(isLoading, message: "Starting activity...")
    }

    private func startActivity() {
        isLoading = true

        let message = [
            "type": "startActivity",
            "activityId": activity.id
        ]
        webSocketService.sendMessage(message: message)

        // Reset loading state after response
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            isLoading = false
        }
    }
}
*/

// MARK: - Example 6: Retry Handler Usage
/*
class DataManager {
    func fetchUserData() async throws -> UserData {
        // Use RetryHandler for network operations
        return try await RetryHandler.shared.retry(
            maxAttempts: 3,
            initialDelay: 1.0,
            maxDelay: 5.0
        ) {
            // Your network call
            try await performNetworkRequest()
        }
    }

    private func performNetworkRequest() async throws -> UserData {
        // Actual network implementation
        throw URLError(.networkConnectionLost)
    }
}
*/

// MARK: - Example 7: Custom Error Handling
/*
struct ShopView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @State private var showCustomError = false
    @State private var customErrorMessage = ""

    var body: some View {
        VStack {
            // Shop items
        }
        // Use error overlay for custom errors
        .errorOverlay(error: $webSocketService.currentError)
        // Or show custom error dialog
        .alert("Error", isPresented: $showCustomError) {
            Button("OK") {
                showCustomError = false
            }
        } message: {
            Text(customErrorMessage)
        }
    }

    private func purchaseItem(itemId: String, cost: Int) {
        // Check if user has enough money before attempting
        guard webSocketService.person.money >= cost else {
            customErrorMessage = "Not enough money. Need \(cost), have \(webSocketService.person.money)."
            showCustomError = true
            return
        }

        let message = [
            "type": "purchaseItem",
            "itemId": itemId
        ]
        webSocketService.sendMessage(message: message)
    }
}
*/

// MARK: - Example 8: Skeleton Loading Variations
/*
struct CustomSkeletonExample: View {
    @State private var isLoading = true

    var body: some View {
        VStack(spacing: AppSpacing.md) {
            // Custom skeleton layout
            if isLoading {
                VStack(spacing: AppSpacing.md) {
                    // Header skeleton
                    HStack {
                        SkeletonAvatar(size: AppSpacing.avatarSizeLarge)
                        VStack(alignment: .leading, spacing: AppSpacing.sm) {
                            SkeletonView()
                                .frame(height: 20)
                                .frame(width: 150)
                            SkeletonView()
                                .frame(height: 16)
                                .frame(width: 100)
                        }
                        Spacer()
                    }

                    // Cards skeleton
                    ForEach(0..<3, id: \.self) { _ in
                        SkeletonCard()
                    }
                }
                .padding()
            } else {
                // Actual content
                ProfileHeader()
                StatsCards()
            }
        }
    }
}
*/

// MARK: - Example 9: Network Operation with Retry
/*
extension WebSocketService {
    func sendMessageWithRetry(_ message: [String: Any]) {
        Task {
            do {
                try await RetryHandler.shared.retry(maxAttempts: 3) {
                    // Wrap sendMessage in async operation
                    try await withCheckedThrowingContinuation { continuation in
                        self.sendMessage(message: message)

                        // Wait for confirmation or timeout
                        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                            if self.isConnected {
                                continuation.resume()
                            } else {
                                continuation.resume(throwing: NSError(
                                    domain: "WebSocket",
                                    code: -1,
                                    userInfo: [NSLocalizedDescriptionKey: "Not connected"]
                                ))
                            }
                        }
                    }
                }
            } catch {
                print("Failed to send message after retries: \(error)")
                // Error will be displayed via errorOverlay
            }
        }
    }
}
*/

// MARK: - Example 10: Complete Integration
/*
struct BaoLifeApp: App {
    @StateObject private var webSocketService = WebSocketService(
        urlSession: URLSession.shared,
        delegateQueue: OperationQueue()
    )
    @StateObject private var storeManager = StoreManager()
    @StateObject private var appViewModel = AppViewModel()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(webSocketService)
                .environmentObject(storeManager)
                .environmentObject(appViewModel)
                // Global error handling
                .errorOverlay(error: $webSocketService.currentError) {
                    webSocketService.reconnect()
                }
                .onAppear {
                    webSocketService.connect()
                }
        }
    }
}
*/
