import SwiftUI

struct BooksInShelfView: View {
    let shelf: ShelfDTO
    @State private var viewModel = LibraryViewModel()
    @State private var showNewBook = false
    @Environment(\.accentTheme) private var theme
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        Group {
            if viewModel.isLoadingBooks && viewModel.books.isEmpty {
                LoadingView(message: L("shelf.loading"))
            } else if viewModel.books.isEmpty && viewModel.error == nil {
                EmptyStateView(
                    systemImage: "book.closed",
                    title: L("shelf.empty.title"),
                    message: L("shelf.empty.message"),
                    actionTitle: L("library.refresh"),
                    action: { Task { await viewModel.loadBooksForShelf(shelfId: shelf.id) } }
                )
            } else {
                List {
                    if let error = viewModel.error {
                        ErrorBanner(error: error) {
                            Task { await viewModel.loadBooksForShelf(shelfId: shelf.id) }
                        }
                        .listRowBackground(Color.clear)
                        .listRowSeparator(.hidden)
                    }

                    Section {
                        BreadcrumbBar(crumbs: [
                            Crumb(label: L("library.title"), action: { dismiss() }),
                            Crumb(label: shelf.name, action: nil)
                        ])
                        .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
                        .listRowBackground(Color.clear)
                        .listRowSeparator(.hidden)
                    }

                    ForEach(viewModel.books) { book in
                        NavigationLink(value: BookInShelf(book: book, shelfName: shelf.name)) {
                            ContentRowView(
                                icon: "book.closed.fill",
                                iconColor: theme.bookColor,
                                name: book.name,
                                description: book.description,
                                updatedAt: book.updatedAt
                            )
                        }
                        .accessibilityLabel("Book: \(book.name)")
                        .contextMenu {
                            Button(role: .destructive) {
                                Task { await viewModel.deleteBook(id: book.id) }
                            } label: {
                                Label(L("book.delete"), systemImage: "trash")
                            }
                        }
                    }
                }
                .listStyle(.insetGrouped)
                .refreshable { await viewModel.loadBooksForShelf(shelfId: shelf.id) }
                .animation(.easeInOut, value: viewModel.books.map(\.id))
            }
        }
        .navigationTitle(shelf.name)
        .navigationBarTitleDisplayMode(.large)
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Button {
                    showNewBook = true
                } label: {
                    Image(systemName: "plus")
                }
                .accessibilityLabel(L("shelf.newbook"))
            }
        }
        .sheet(isPresented: $showNewBook) {
            NewBookView(preselectedShelf: shelf)
        }
        .onChange(of: showNewBook) { _, isShowing in
            if !isShowing { Task { await viewModel.loadBooksForShelf(shelfId: shelf.id) } }
        }
        .task { await viewModel.loadBooksForShelf(shelfId: shelf.id) }
    }
}

#Preview("Books in Shelf") {
    NavigationStack {
        List {
            ForEach(BookDTO.mockList) { book in
                ContentRowView(
                    icon: "book.closed.fill",
                    iconColor: AccentTheme.ocean.bookColor,
                    name: book.name,
                    description: book.description,
                    updatedAt: book.updatedAt
                )
            }
        }
        .listStyle(.insetGrouped)
        .navigationTitle("Engineering Docs")
    }
}
