import SwiftUI

// MARK: - New Book View

struct NewBookView: View {
    var preselectedShelf: ShelfDTO? = nil
    @State private var name = ""
    @State private var bookDescription = ""
    @State private var shelves: [ShelfDTO] = []
    @State private var selectedShelf: ShelfDTO? = nil
    @State private var isLoadingShelves = true
    @State private var isSaving = false
    @State private var error: BookStackError?
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Form {
                Section(L("create.book.details")) {
                    TextField(L("create.book.name"), text: $name)
                    TextField(L("create.description"), text: $bookDescription)
                }

                Section {
                    if isLoadingShelves {
                        HStack {
                            ProgressView().controlSize(.small)
                            Text(L("create.book.shelf.loading"))
                                .foregroundStyle(.secondary)
                                .padding(.leading, 8)
                        }
                    } else {
                        Picker(L("create.shelf.title"), selection: $selectedShelf) {
                            Text(L("create.book.shelf.none")).tag(ShelfDTO?.none)
                            ForEach(shelves) { shelf in
                                Text(shelf.name).tag(ShelfDTO?.some(shelf))
                            }
                        }
                    }
                } header: {
                    Text(L("create.book.shelf.header"))
                } footer: {
                    Text(L("create.book.shelf.footer"))
                }

                if let error {
                    Section {
                        ErrorBanner(error: error)
                            .listRowBackground(Color.clear)
                    }
                }
            }
            .navigationTitle(L("create.book.title"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button(L("create.cancel")) { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    if isSaving {
                        ProgressView().controlSize(.small)
                    } else {
                        Button(L("create.create")) {
                            Task { await save() }
                        }
                        .disabled(name.isEmpty)
                    }
                }
            }
            .task {
                shelves = (try? await BookStackAPI.shared.fetchShelves()) ?? []
                isLoadingShelves = false
                if let preselected = preselectedShelf {
                    selectedShelf = shelves.first { $0.id == preselected.id } ?? preselected
                }
            }
        }
    }

    private func save() async {
        isSaving = true
        error = nil
        do {
            let book = try await BookStackAPI.shared.createBook(name: name, bookDescription: bookDescription)
            // If a shelf was selected, append this book to it
            if let shelf = selectedShelf {
                // Fetch current book IDs on the shelf, then append the new one
                let current = (try? await BookStackAPI.shared.fetchShelf(id: shelf.id))?.books.map(\.id) ?? []
                try await BookStackAPI.shared.updateShelfBooks(shelfId: shelf.id, bookIds: current + [book.id])
            }
            dismiss()
        } catch let e as BookStackError {
            self.error = e
        } catch {
            self.error = .unknown(error.localizedDescription)
        }
        isSaving = false
    }
}

// MARK: - New Shelf View

struct NewShelfView: View {
    @State private var name = ""
    @State private var shelfDescription = ""
    @State private var isSaving = false
    @State private var error: BookStackError?
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            Form {
                Section(L("create.shelf.details")) {
                    TextField(L("create.shelf.name"), text: $name)
                    TextField(L("create.description"), text: $shelfDescription)
                }
                if let error {
                    Section {
                        ErrorBanner(error: error)
                            .listRowBackground(Color.clear)
                    }
                }
            }
            .navigationTitle(L("create.shelf.title"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button(L("create.cancel")) { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button(L("create.create")) {
                        Task { await save() }
                    }
                    .disabled(name.isEmpty || isSaving)
                }
            }
        }
    }

    private func save() async {
        isSaving = true
        error = nil
        do {
            _ = try await BookStackAPI.shared.createShelf(name: name, shelfDescription: shelfDescription)
            dismiss()
        } catch let e as BookStackError {
            self.error = e
        } catch {
            self.error = .unknown(error.localizedDescription)
        }
        isSaving = false
    }
}

#Preview("New Shelf") {
    NewShelfView()
}
#Preview("New Book") {
    NewBookView()
}

