//
// OpenRocky — Voice-first AI Agent
// https://github.com/openrocky
//
// Developed by everettjf with the assistance of Claude Code and Codex.
// Date: 2026-05-04
// Copyright (c) 2026 everettjf. All rights reserved.
//

import SwiftUI

struct OpenRockyMCPServersListView: View {
    @ObservedObject var store: OpenRockyMCPStore
    @State private var presentingNewServer = false

    var body: some View {
        List {
            Section {
                Button {
                    presentingNewServer = true
                } label: {
                    Label("Add MCP Server", systemImage: "plus.circle")
                }
            } footer: {
                Text("MCP servers expose tools to the chat sub-agent (called via delegate-task). Voice doesn't see them directly.")
            }

            if !store.servers.isEmpty {
                Section {
                    ForEach(store.servers) { server in
                        serverRow(server)
                    }
                    .onDelete { indexSet in
                        let ids = indexSet.map { store.servers[$0].id }
                        for id in ids { store.delete(id: id) }
                    }
                } header: {
                    Text("Installed (\(store.servers.count))")
                } footer: {
                    let enabledCount = store.servers.filter(\.isEnabled).count
                    Text("\(enabledCount) of \(store.servers.count) enabled")
                }
            }
        }
        .navigationTitle("MCP Servers")
        .navigationBarTitleDisplayMode(.inline)
        .sheet(isPresented: $presentingNewServer) {
            NavigationStack {
                OpenRockyMCPServerEditorView(store: store, editingServerID: nil)
            }
        }
    }

    @ViewBuilder
    private func serverRow(_ server: OpenRockyMCPServer) -> some View {
        NavigationLink {
            OpenRockyMCPServerEditorView(store: store, editingServerID: server.id)
        } label: {
            HStack {
                VStack(alignment: .leading, spacing: 2) {
                    Text(server.label)
                        .fontWeight(.medium)
                    HStack(spacing: 6) {
                        if server.cachedTools.isEmpty {
                            Text("No tools cached — tap to refresh")
                                .font(.caption)
                                .foregroundStyle(.secondary)
                        } else {
                            Text("\(server.cachedTools.count) tool\(server.cachedTools.count == 1 ? "" : "s")")
                                .font(.caption)
                                .foregroundStyle(.secondary)
                        }
                        if let date = server.lastRefreshedAt {
                            Text("· \(Self.relativeFormatter.localizedString(for: date, relativeTo: Date()))")
                                .font(.caption)
                                .foregroundStyle(.secondary)
                        }
                    }
                }
                Spacer()
                Toggle("", isOn: Binding(
                    get: { server.isEnabled },
                    set: { _ in store.toggle(id: server.id) }
                ))
                .labelsHidden()
            }
        }
        .swipeActions(edge: .trailing) {
            Button(role: .destructive) {
                store.delete(id: server.id)
            } label: {
                Label("Delete", systemImage: "trash")
            }
        }
    }

    private static let relativeFormatter: RelativeDateTimeFormatter = {
        let f = RelativeDateTimeFormatter()
        f.unitsStyle = .abbreviated
        return f
    }()
}
