import SwiftUI

struct GroupFormView: View {
    enum Mode {
        case add
        case edit(ServerGroup)
    }

    let mode: Mode
    @Binding var groups: [ServerGroup]
    let onSave: () -> Void

    @Environment(\.dismiss) private var dismiss
    @State private var name: String

    init(mode: Mode, groups: Binding<[ServerGroup]>, onSave: @escaping () -> Void) {
        self.mode = mode
        self._groups = groups
        self.onSave = onSave

        switch mode {
        case .add:
            self._name = State(initialValue: "")
        case .edit(let group):
            self._name = State(initialValue: group.name)
        }
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text(title)
                .font(.headline)

            TextField("Group name", text: $name)
                .textFieldStyle(.roundedBorder)

            HStack {
                Button("Cancel") {
                    dismiss()
                }

                Spacer()

                Button("Save") {
                    save()
                }
                .disabled(trimmedName.isEmpty)
            }
        }
        .padding()
        .frame(width: 320)
    }

    private var title: String {
        switch mode {
        case .add:
            return "Add Group"
        case .edit:
            return "Edit Group"
        }
    }

    private var trimmedName: String {
        name.trimmingCharacters(in: .whitespacesAndNewlines)
    }

    private func save() {
        switch mode {
        case .add:
            groups.append(ServerGroup(name: trimmedName))
        case .edit(let group):
            if let index = groups.firstIndex(where: { $0.id == group.id }) {
                groups[index].name = trimmedName
            }
        }

        onSave()
        dismiss()
    }
}
