import SwiftUI

struct SidebarView: View {
    @Environment(AppModel.self) private var model
    @State private var showingNewFolderSheet = false
    @State private var selection: String = ""

    var body: some View {
        List(selection: $selection) {
            Section("Stations") {
                pageRow(.top)
                pageRow(.germany)
                pageRow(.netherlands)
                pageRow(.world)
                pageRow(.search, badge: model.library.selectedPage == .search ? model.library.stations.count : nil)
            }
            Section("Library") {
                pageRow(.favorites, badge: model.library.favorites.count)
                pageRow(.recent, badge: model.library.recentStations.count)
                pageRow(.manual, badge: model.library.manualStations.count)
            }
            if !model.library.groups.isEmpty {
                Section("Folders") {
                    ForEach(model.library.groups.sorted { $0.sortOrder < $1.sortOrder }) { group in
                        GroupRowView(group: group)
                    }
                }
            }
        }
        .onAppear {
            updateSelection()
        }
        .onChange(of: model.library.selectedPage) { _, _ in updateSelection() }
        .onChange(of: model.library.selectedGroupID) { _, _ in updateSelection() }
        .onChange(of: selection) { _, newValue in
            handleSelectionChange(newValue)
        }
        .listStyle(.sidebar)
        .navigationSplitViewColumnWidth(min: 190, ideal: 220, max: 280)
        .contextMenu {
            Button("New Folder") {
                showingNewFolderSheet = true
            }
        }
        .sheet(isPresented: $showingNewFolderSheet) {
            NewGroupView()
                .environment(model)
        }
    }

    private func updateSelection() {
        if model.library.selectedPage == .group {
            selection = model.library.selectedGroupID ?? ""
        } else {
            selection = model.library.selectedPage.rawValue
        }
    }

    private func handleSelectionChange(_ value: String) {
        if let group = model.library.groups.first(where: { $0.id == value }) {
            model.library.selectGroup(group)
        } else if let page = StationPage(rawValue: value) {
            Task { await model.library.load(page) }
        }
    }

    private func pageRow(_ page: StationPage, badge: Int? = nil) -> some View {
        HStack {
            Label(page.title, systemImage: page.systemImage)
            Spacer()
            if let badge, badge > 0 {
                Text(badge, format: .number)
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
        }
        .tag(page.rawValue)
    }
}
