import SwiftUI
import SwiftData
import SFSafeSymbols

struct SettingsView: View {

    let keyManager: KeyManagement
    
    @ObservedObject
    var coordinator: RequestCoordinator
    
    @Binding
    var serverAddress: String
    
    @Binding
    var localAddress: String
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(alignment: .leading, spacing: 8) {
                    VStack(alignment: .leading) {
                        Text("Server address")
                            .bold()
                        TextField("Server address", text: $serverAddress)
                            .foregroundColor(.secondary)
                            .padding(.leading, 8)
                        HStack {
                            Button("Test") {
                                coordinator.checkConnection(using: .throughServer)
                            }.padding(8)
                            if coordinator.state == .deviceAvailable {
                                Image(systemSymbol: .checkmarkCircle)
                                    .foregroundColor(.green)
                            } else if coordinator.state != .notChecked {
                                Text(coordinator.state.description)
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                            }
                        }
                    }.padding(.vertical, 8)
                    VStack(alignment: .leading) {
                        Text("Local address")
                            .bold()
                        TextField("Local address", text: $localAddress)
                            .foregroundColor(.secondary)
                            .padding(.leading, 8)
                    }.padding(.vertical, 8)
                    ForEach(KeyManagement.KeyType.allCases) { keyType in
                        SingleKeyView(
                            keyManager: keyManager,
                            type: keyType)
                    }
                }.padding()
            }.onDisappear {
                if !localAddress.hasSuffix("/") {
                    localAddress += "/"
                }
            }
            .navigationTitle("Settings")
        }
    }
}

#Preview {
    do {
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(for: HistoryItem.self, configurations: config)
        
        let item = HistoryItem.mock
        container.mainContext.insert(item)
        try container.mainContext.save()
        return SettingsView(
            keyManager: KeyManagement(),
            coordinator: .init(modelContext: container.mainContext),
            serverAddress: .constant("https://example.com"),
            localAddress: .constant("192.168.178.42"))
    } catch {
        fatalError("Failed to create model container.")
    }
}
