import ForgejoKit
import SwiftData
import SwiftUI

struct InstanceListView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(sort: \ForgejoInstance.lastUsed, order: .reverse) private var instances: [ForgejoInstance]
    @AppStorage("defaultAllInstances") private var defaultAllInstances = false
    @State private var authService: AuthenticationService
    @Binding var multiInstanceManager: MultiInstanceManager?
    @State private var showAddSheet = false
    @State private var editingInstance: ForgejoInstance?
    @State private var connectingInstance: ForgejoInstance?
    @State private var connectingAll = false
    @State private var errorMessage: String?
    @State private var showError = false

    init(authService: AuthenticationService, multiInstanceManager: Binding<MultiInstanceManager?>) {
        self.authService = authService
        _multiInstanceManager = multiInstanceManager
    }

    var body: some View {
        NavigationStack {
            Group {
                if instances.isEmpty {
                    ContentUnavailableView {
                        Label("No Instances", systemImage: "server.rack")
                            .foregroundStyle(.blue)
                    } description: {
                        Text("Add your first Forgejo instance to get started.")
                    }
                } else {
                    List {
                        if instances.count > 1 {
                            allInstancesRow
                                .swipeActions(edge: .leading, allowsFullSwipe: true) {
                                    Button {
                                        toggleDefaultAll()
                                    } label: {
                                        Label(
                                            defaultAllInstances ? "Unset Default" : "Set Default",
                                            systemImage: defaultAllInstances ? "star.slash" : "star.fill",
                                        )
                                    }
                                    .tint(.yellow)
                                }
                        }
                        ForEach(instances) { instance in
                            instanceRow(instance)
                                .swipeActions(edge: .trailing, allowsFullSwipe: false) {
                                    Button(role: .destructive) {
                                        deleteInstance(instance)
                                    } label: {
                                        Label("Delete", systemImage: "trash")
                                    }
                                }
                                .swipeActions(edge: .leading, allowsFullSwipe: true) {
                                    Button {
                                        toggleDefault(instance)
                                    } label: {
                                        Label(
                                            instance.isDefault ? "Unset Default" : "Set Default",
                                            systemImage: instance.isDefault ? "star.slash" : "star.fill",
                                        )
                                    }
                                    .tint(.yellow)
                                }
                        }
                    }
                    .accessibilityIdentifier("instance-list")
                }
            }
            .navigationTitle("Instances")
            .toolbar {
                ToolbarItem(placement: .primaryAction) {
                    Button {
                        showAddSheet = true
                    } label: {
                        Image(systemName: "plus")
                    }
                    .accessibilityLabel("Add instance")
                    .accessibilityIdentifier("instance-add-button")
                }
            }
            .sheet(isPresented: $showAddSheet) {
                InstanceFormView(authService: authService, mode: .add)
            }
            .sheet(item: $editingInstance) { instance in
                InstanceFormView(authService: authService, mode: .edit(instance))
            }
            .errorAlert("Connection Failed", message: $errorMessage, isPresented: $showError)
        }
    }

    private func instanceRow(_ instance: ForgejoInstance) -> some View {
        Button {
            connect(to: instance)
        } label: {
            HStack {
                VStack(alignment: .leading, spacing: 4) {
                    HStack(spacing: 8) {
                        Text(instance.name.isEmpty ? instance.serverURL : instance.name)
                            .font(.headline)
                        if instance.isDefault {
                            Text("Default")
                                .font(.caption2)
                                .fontWeight(.medium)
                                .padding(.horizontal, 6)
                                .padding(.vertical, 2)
                                .glassEffect(.regular.tint(.yellow))
                        }
                    }
                    Text(instance.serverURL)
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                    Text("@\(instance.username)")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
                Spacer()
                if connectingInstance?.id == instance.id {
                    ProgressView()
                } else {
                    Button {
                        editingInstance = instance
                    } label: {
                        Image(systemName: "pencil.circle.fill")
                            .font(.title3)
                            .foregroundStyle(.secondary)
                    }
                    .buttonStyle(.plain)
                    .accessibilityLabel("Edit instance")
                    .accessibilityIdentifier("instance-edit-button")
                }
            }
        }
        .disabled(connectingInstance != nil)
        .accessibilityIdentifier("instance-row")
    }

    private var allInstancesRow: some View {
        Button {
            connectAll()
        } label: {
            HStack {
                VStack(alignment: .leading, spacing: 4) {
                    HStack(spacing: 8) {
                        Text("All Instances")
                            .font(.headline)
                        if defaultAllInstances {
                            Text("Default")
                                .font(.caption2)
                                .fontWeight(.medium)
                                .padding(.horizontal, 6)
                                .padding(.vertical, 2)
                                .glassEffect(.regular.tint(.yellow))
                        }
                    }
                    Text("\(instances.count) instances")
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                }
                Spacer()
                if connectingAll {
                    ProgressView()
                } else {
                    Image(systemName: "rectangle.stack.fill")
                        .foregroundStyle(.blue)
                        .font(.title3)
                }
            }
        }
        .disabled(connectingInstance != nil || connectingAll)
        .accessibilityIdentifier("all-instances-row")
    }

    private func connectAll() {
        connectingAll = true
        let manager = MultiInstanceManager()
        Task {
            await manager.connect(instances: instances)
            if manager.isConnected {
                multiInstanceManager = manager
            } else {
                errorMessage = "Could not connect to any instance"
                showError = true
            }
            connectingAll = false
        }
    }

    private func connect(to instance: ForgejoInstance) {
        connectingInstance = instance
        Task {
            do {
                try await authService.restoreSession(instance: instance)
                instance.lastUsed = Date()
                do {
                    try modelContext.save()
                } catch {
                    assertionFailure("SwiftData save failed: \(error)")
                }
            } catch is KeychainError {
                editingInstance = instance
            } catch {
                errorMessage = error.localizedDescription
                showError = true
            }
            connectingInstance = nil
        }
    }

    private func deleteInstance(_ instance: ForgejoInstance) {
        // Disconnect if deleting the currently active instance
        if authService.currentInstance?.id == instance.id {
            authService.disconnect()
        }
        let normalizedURL = ForgejoClient.normalizeServerURL(instance.serverURL)
        let username = instance.username
        modelContext.delete(instance)
        do {
            try modelContext.save()
        } catch {
            assertionFailure("SwiftData save failed: \(error)")
        }
        Task {
            try? await KeychainManager.shared.deleteCredentials(for: normalizedURL, username: username)
        }
    }

    private func toggleDefaultAll() {
        defaultAllInstances.toggle()
        if defaultAllInstances {
            ForgejoInstance.clearDefaults(in: instances)
            do {
                try modelContext.save()
            } catch {
                assertionFailure("SwiftData save failed: \(error)")
            }
        }
    }

    private func toggleDefault(_ instance: ForgejoInstance) {
        if instance.isDefault {
            instance.isDefault = false
        } else {
            ForgejoInstance.clearDefaults(in: instances)
            instance.isDefault = true
            defaultAllInstances = false
        }
        do {
            try modelContext.save()
        } catch {
            assertionFailure("SwiftData save failed: \(error)")
        }
    }
}

#if DEBUG
    #Preview {
        InstanceListView(authService: .previewDefault, multiInstanceManager: .constant(nil))
            .modelContainer(for: ForgejoInstance.self, inMemory: true)
    }
#endif
