import SwiftUI
import Models

struct LabelPicker: View {
	let labels: [LabelInfo]
	let onSelect: (LabelInfo) -> Void
	let onCreate: (String) -> Void
	@Environment(\.dismiss) private var dismiss
	@State private var searchText = ""

	private var filteredLabels: [LabelInfo] {
		if searchText.isEmpty {
			return labels
		}
		return labels.filter { $0.name.localizedCaseInsensitiveContains(searchText) }
	}

	private var showCreateOption: Bool {
		let trimmed = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
		guard !trimmed.isEmpty else { return false }
		return !labels.contains { $0.name.lowercased() == trimmed.lowercased() }
	}

	var body: some View {
		NavigationStack {
			List {
				if showCreateOption {
					Button {
						let name = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
						onCreate(name)
						dismiss()
					} label: {
						Label("Create project: \(searchText.trimmingCharacters(in: .whitespacesAndNewlines))", systemImage: "plus.circle")
					}
				}

				ForEach(filteredLabels) { label in
					Button {
						onSelect(label)
						dismiss()
					} label: {
						Label(label.name, systemImage: label.isProject ? "folder.fill" : "tag")
					}
				}
			}
			.searchable(text: $searchText, prompt: "Search or create project")
			.navigationTitle("Projects")
			.toolbar {
				ToolbarItem(placement: .cancellationAction) {
					Button("Cancel") {
						dismiss()
					}
				}
			}
		}
		.frame(minWidth: 300, minHeight: 300)
	}
}
