import SwiftUI

struct TaskEditView: View {
	@Bindable var viewModel: TaskEditViewModel
	@Environment(\.dismiss) private var dismiss

	var body: some View {
		NavigationStack {
			Form {
				Section {
					TextField("Title", text: $viewModel.title)
						.textFieldStyle(.plain)
				}

				Section {
					TextEditor(text: $viewModel.body)
						.frame(minHeight: 80)
				} header: {
					Text("Notes")
				}

				Section {
					Toggle("Due Date", isOn: $viewModel.hasDueDate)
					if viewModel.hasDueDate {
						DatePicker(
							"Due",
							selection: Binding(
								get: { viewModel.dueDate ?? Date() },
								set: { viewModel.dueDate = $0 }
							),
							displayedComponents: .date
						)
					}
				}
			}
			.formStyle(.grouped)
			.navigationTitle("New Task")
			.toolbar {
				ToolbarItem(placement: .cancellationAction) {
					Button("Cancel") {
						dismiss()
					}
				}
				ToolbarItem(placement: .confirmationAction) {
					Button("Save") {
						saveTask()
					}
					.keyboardShortcut(.return, modifiers: .command)
					.disabled(!viewModel.canSave)
				}
			}
			.alert("Error", isPresented: .constant(viewModel.errorMessage != nil)) {
				Button("OK") { viewModel.errorMessage = nil }
			} message: {
				if let msg = viewModel.errorMessage {
					Text(msg)
				}
			}
		}
		.frame(minWidth: 400, minHeight: 300)
	}

	private func saveTask() {
		do {
			try viewModel.save()
			dismiss()
		} catch {
			viewModel.errorMessage = error.localizedDescription
		}
	}
}
