import SwiftUI

struct TodoFormView: View {
    let editingTodo: Todo?
    let onSave: (String, String, Priority) -> Void
    let onCancel: () -> Void

    @State private var title: String = ""
    @State private var selectedCategory: String = "Personal"
    @State private var selectedPriority: Priority = .medium

    private var isEditing: Bool {
        editingTodo != nil
    }

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    TextField("What needs to be done?", text: $title)
                        .textInputAutocapitalization(.sentences)
                }

                Section {
                    CategoryPicker(selectedCategory: $selectedCategory)
                }
                .listRowInsets(EdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16))

                Section {
                    PriorityPicker(selectedPriority: $selectedPriority)
                }
                .listRowInsets(EdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16))
            }
            .navigationTitle(isEditing ? "Edit Todo" : "Add New Todo")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") {
                        onCancel()
                    }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button(isEditing ? "Save" : "Add") {
                        let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
                        guard !trimmed.isEmpty else { return }
                        onSave(trimmed, selectedCategory, selectedPriority)
                    }
                    .fontWeight(.semibold)
                    .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
                }
            }
            .onAppear {
                if let todo = editingTodo {
                    title = todo.title
                    selectedCategory = todo.category
                    selectedPriority = todo.priority
                }
            }
        }
    }
}
