import SwiftUI

struct GroupRowView: View {
    @Environment(AppModel.self) private var model
    let group: StationGroup
    @State private var showingRenameSheet = false

    var body: some View {
        HStack {
            Label(group.name, systemImage: "folder.fill")
            Spacer()
            Text(group.stationIDs.count, format: .number)
                .font(.caption)
                .foregroundStyle(.secondary)
        }
        .tag(group.id)
        .contextMenu {
            Button("Rename") {
                showingRenameSheet = true
            }
            Button("Delete") {
                model.library.deleteGroup(group)
            }
        }
        .sheet(isPresented: $showingRenameSheet) {
            RenameGroupView(group: group)
                .environment(model)
        }
    }
}

struct RenameGroupView: View {
    @Environment(AppModel.self) private var model
    @Environment(\.dismiss) private var dismiss
    let group: StationGroup
    @State private var name = ""

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("Rename folder")
                .font(.title2.bold())

            TextField("Folder name", text: $name)
                .textFieldStyle(.roundedBorder)
                .onAppear { name = group.name }

            HStack {
                Spacer()
                Button("Cancel") { dismiss() }
                Button("Rename") {
                    model.library.renameGroup(group, to: name)
                    dismiss()
                }
                .keyboardShortcut(.defaultAction)
                .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
            }
        }
        .padding(24)
        .frame(width: 340)
    }
}
