import SwiftUI

struct MergedConnectionWarning: View {
    let failedInstances: [(instance: ForgejoInstance, error: String)]

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Label("Some instances failed to connect", systemImage: "exclamationmark.triangle.fill")
                .font(.caption)
                .fontWeight(.medium)
                .foregroundStyle(.orange)
            ForEach(failedInstances, id: \.instance.id) { failed in
                let name = failed.instance.name.isEmpty ? failed.instance.serverURL : failed.instance.name
                Text("\(name): \(failed.error)")
                    .font(.caption2)
                    .foregroundStyle(.secondary)
            }
        }
        .padding(.horizontal)
        .padding(.vertical, 8)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(.ultraThinMaterial)
        .accessibilityIdentifier("merged-connection-status")
    }
}

struct MergedCreatePickerView<Content: View>: View {
    let manager: MultiInstanceManager
    @ViewBuilder let content: (ForgejoInstance, AuthenticationService) -> Content
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            List {
                Section("Select Instance") {
                    ForEach(manager.connections, id: \.instance.id) { connection in
                        NavigationLink {
                            content(connection.instance, connection.authService)
                        } label: {
                            VStack(alignment: .leading, spacing: 4) {
                                Text(manager.displayName(for: connection.instance))
                                    .font(.headline)
                                Text(connection.instance.serverURL)
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                            }
                        }
                    }
                }
            }
            .navigationTitle("Choose Instance")
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
            }
        }
    }
}
