struct AddBook: View {
   @Environment(ApplicationData.self) private var appData
   @Environment(\.modelContext) var dbContext
   @State private var titleInput: String = ""
   @State private var yearInput: String = ""
   
   var body: some View {
      VStack(alignment: .leading, spacing: 10) {
         TextField("Insert Title", text: $titleInput)
            .textFieldStyle(.roundedBorder)
         TextField("Insert Year", text: $yearInput)
            .textFieldStyle(.roundedBorder)
            .keyboardType(.numbersAndPunctuation)
         VStack(alignment: .leading) {
            Text("Author")
            NavigationLink(value: "List Authors", label: {
               Text(appData.selectedAuthor?.name ?? "Select")
            })
         }
         HStack {
            Spacer()
            Button("Save") {
               storeBook()
            }.buttonStyle(.borderedProminent)
         }
         Spacer()
      }.padding()
      .onAppear {
         if let selectedBook = appData.selectedBook, titleInput.isEmpty && yearInput.isEmpty {
            titleInput = selectedBook.title
            yearInput = selectedBook.displayYear
         }
      }
   }
   func storeBook() {
      let title = titleInput.trimmingCharacters(in: .whitespaces)
      if let year = Int(yearInput), !title.isEmpty {
         if let oldBook = appData.selectedBook {
            oldBook.title = title
            oldBook.year = year
            oldBook.author = appData.selectedAuthor
            try? dbContext.save()
         } else {
            let newBook = Book(title: title, author: appData.selectedAuthor, cover: "nocover", year: year)
            dbContext.insert(newBook)
            try? dbContext.save()
         }
         appData.selectedAuthor = nil
         appData.selectedBook = nil
         appData.viewPath.removeLast()
      }
   }
}