import SwiftUI

/// Sheet-based filter picker. Backs the Live tab's airline + aircraft-type
/// filters. Uses a real `List` (virtualized, smooth scrolling) instead of
/// SwiftUI's `Menu`, which renders all items eagerly in a popover and
/// stutters once the count goes past ~20.
///
/// Multi-select. Tap-to-toggle. Search-as-you-type filters the list.
struct LiveFilterPicker: View {
    let title: String
    let items: [Item]
    @Binding var selection: Set<String>

    @Environment(\.dismiss) private var dismiss
    @State private var query: String = ""

    struct Item: Hashable, Identifiable {
        let id: String
        let label: String
        let count: Int
    }

    private var filteredItems: [Item] {
        let q = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        if q.isEmpty { return items }
        return items.filter { $0.label.lowercased().contains(q) || $0.id.lowercased().contains(q) }
    }

    var body: some View {
        NavigationStack {
            List {
                if !selection.isEmpty {
                    Section {
                        ForEach(items.filter { selection.contains($0.id) }) { item in
                            row(item)
                        }
                        Button(role: .destructive) {
                            selection.removeAll()
                        } label: {
                            Label("Clear selection", systemImage: "xmark.circle")
                        }
                    } header: {
                        Text("Selected (\(selection.count))")
                    }
                }

                Section {
                    ForEach(filteredItems.filter { !selection.contains($0.id) }) { item in
                        row(item)
                    }
                } header: {
                    if !selection.isEmpty {
                        Text("All")
                    }
                }
            }
            .listStyle(.insetGrouped)
            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always),
                        prompt: "Search \(title.lowercased())")
            .navigationTitle(title)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") { dismiss() }
                        .fontWeight(.semibold)
                }
            }
        }
    }

    private func row(_ item: Item) -> some View {
        Button {
            toggle(item.id)
        } label: {
            HStack {
                Image(systemName: selection.contains(item.id) ? "checkmark.circle.fill" : "circle")
                    .foregroundStyle(selection.contains(item.id) ? FlightTheme.accent : FlightTheme.textTertiary)
                Text(item.label)
                    .foregroundStyle(FlightTheme.textPrimary)
                Spacer()
                Text("\(item.count)")
                    .font(.caption.monospacedDigit())
                    .foregroundStyle(FlightTheme.textSecondary)
            }
        }
        .buttonStyle(.plain)
    }

    private func toggle(_ id: String) {
        if selection.contains(id) {
            selection.remove(id)
        } else {
            selection.insert(id)
        }
    }
}
