import Foundation
import Network
import SwiftUI

class NetworkPermissionManager: ObservableObject {
    @Published var isNetworkAvailable = false
    @Published var isCheckingNetwork = true
    @Published var showNetworkPermissionAlert = false
    
    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "NetworkMonitor")
    
    init() {
        startNetworkMonitoring()
    }
    
    deinit {
        monitor.cancel()
    }
    
    private func startNetworkMonitoring() {
        monitor.pathUpdateHandler = { [weak self] path in
            DispatchQueue.main.async {
                self?.isNetworkAvailable = path.status == .satisfied
                self?.isCheckingNetwork = false
                
                // 如果网络不可用，显示权限提示
                if path.status != .satisfied {
                    self?.showNetworkPermissionAlert = true
                }
            }
        }
        monitor.start(queue: queue)
    }
    
    func checkNetworkPermission() {
        isCheckingNetwork = true
        // 重新开始监控
        monitor.cancel()
        startNetworkMonitoring()
    }
    
    func openNetworkSettings() {
        if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl)
            }
        }
    }
}

// 网络权限检查视图
struct NetworkPermissionView: View {
    @ObservedObject var networkManager: NetworkPermissionManager
    let onPermissionGranted: () -> Void
    
    var body: some View {
        VStack(spacing: 30) {
            // 网络图标
            Image(systemName: "wifi.slash")
                .font(.system(size: 80, weight: .light))
                .foregroundColor(.white.opacity(0.8))
            
            VStack(spacing: 15) {
                Text("network_permission_required".localized)
                    .font(.system(size: 28, weight: .bold))
                    .foregroundColor(.white)
                
                Text("network_permission_description".localized)
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(.white.opacity(0.8))
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 40)
            }
            
            VStack(spacing: 20) {
                // 检查网络按钮
                Button(action: {
                    networkManager.checkNetworkPermission()
                }) {
                    HStack {
                        if networkManager.isCheckingNetwork {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                .scaleEffect(0.8)
                        } else {
                            Image(systemName: "arrow.clockwise")
                        }
                        Text(networkManager.isCheckingNetwork ? "checking_network".localized : "check_network".localized)
                    }
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .frame(height: 50)
                    .background(
                        RoundedRectangle(cornerRadius: 25)
                            .fill(Color.white.opacity(0.2))
                    )
                }
                .disabled(networkManager.isCheckingNetwork)
                
                // 打开设置按钮
                Button(action: {
                    networkManager.openNetworkSettings()
                }) {
                    HStack {
                        Image(systemName: "gear")
                        Text("open_settings".localized)
                    }
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .frame(height: 50)
                    .background(
                        RoundedRectangle(cornerRadius: 25)
                            .fill(Color.blue.opacity(0.8))
                    )
                }
            }
            .padding(.horizontal, 40)
        }
        .onChange(of: networkManager.isNetworkAvailable) { isAvailable in
            if isAvailable {
                onPermissionGranted()
            }
        }
    }
}
