import SwiftUI

struct LibraryView: View {
    @State private var viewModel = LibraryViewModel()
    @State private var showNewShelf = false
    @Environment(ConnectivityMonitor.self) private var connectivity
    @Environment(\.accentTheme) private var theme

    var body: some View {
        NavigationStack {
            Group {
                if viewModel.isLoadingShelves && viewModel.shelves.isEmpty {
                    LoadingView(message: L("library.loading"))
                } else if viewModel.shelves.isEmpty && viewModel.error == nil {
                    EmptyStateView(
                        systemImage: "books.vertical",
                        title: L("library.empty.title"),
                        message: L("library.empty.message"),
                        actionTitle: L("library.refresh"),
                        action: { Task { await viewModel.loadShelves() } }
                    )
                } else {
                    List {
                        if let error = viewModel.error {
                            ErrorBanner(error: error) {
                                Task { await viewModel.loadShelves() }
                            }
                            .listRowBackground(Color.clear)
                            .listRowSeparator(.hidden)
                        }

                        Section(L("library.shelves")) {
                            ForEach(viewModel.shelves) { shelf in
                                NavigationLink(value: shelf) {
                                    ContentRowView(
                                        icon: "books.vertical.fill",
                                        iconColor: theme.shelfColor,
                                        name: shelf.name,
                                        description: shelf.description,
                                        updatedAt: shelf.updatedAt
                                    )
                                }
                                .accessibilityLabel("Shelf: \(shelf.name)")
                            }
                        }
                    }
                    .listStyle(.insetGrouped)
                    .refreshable { await viewModel.loadShelves() }
                    .animation(.easeInOut, value: viewModel.shelves.map(\.id))
                }
            }
            .navigationTitle(L("library.title"))
            .toolbar {
                ToolbarItem(placement: .primaryAction) {
                    Button {
                        showNewShelf = true
                    } label: {
                        Image(systemName: "plus")
                    }
                    .accessibilityLabel(L("library.newshelf"))
                }
            }
            .sheet(isPresented: $showNewShelf) {
                NewShelfView()
            }
            .onChange(of: showNewShelf) { _, isShowing in
                if !isShowing { Task { await viewModel.loadShelves() } }
            }
            .navigationDestination(for: ShelfDTO.self) { shelf in
                BooksInShelfView(shelf: shelf)
            }
            .navigationDestination(for: BookDTO.self) { book in
                BookDetailView(book: book, shelfName: nil)
            }
            .navigationDestination(for: BookInShelf.self) { item in
                BookDetailView(book: item.book, shelfName: item.shelfName)
            }
            .navigationDestination(for: PageDTO.self) { page in
                PageReaderView(page: page)
            }
            .safeAreaInset(edge: .top) {
                if !connectivity.isConnected {
                    OfflineBanner()
                }
            }
        }
        .task { await viewModel.loadShelves() }
    }
}

// MARK: - Navigation helper

/// Wraps a BookDTO with its parent shelf name so BookDetailView can show a full breadcrumb.
struct BookInShelf: Hashable {
    let book: BookDTO
    let shelfName: String
}

// MARK: - Breadcrumb bar

/// Crumb model: a label and an optional tap action (nil = current page, not tappable).
struct Crumb {
    let label: String
    let action: (() -> Void)?
}

struct BreadcrumbBar: View {
    let crumbs: [Crumb]
    @Environment(\.accentTheme) private var theme

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 0) {
                ForEach(Array(crumbs.enumerated()), id: \.offset) { index, crumb in
                    if index > 0 {
                        Image(systemName: "chevron.right")
                            .font(.footnote.weight(.semibold))
                            .foregroundStyle(.tertiary)
                            .padding(.horizontal, 6)
                    }
                    let isLast = index == crumbs.count - 1
                    if let action = crumb.action {
                        Button(action: action) {
                            Text(crumb.label)
                                .font(.subheadline.weight(.medium))
                                .foregroundStyle(theme.accentColor)
                                .lineLimit(1)
                                .fixedSize()
                        }
                        .buttonStyle(.plain)
                    } else {
                        Text(crumb.label)
                            .font(.subheadline.weight(isLast ? .semibold : .medium))
                            .foregroundStyle(isLast ? .primary : .secondary)
                            .lineLimit(1)
                            .fixedSize()
                    }
                }
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 8)
        }
    }
}

// MARK: - Reusable content row

struct ContentRowView: View {
    let icon: String
    let iconColor: Color
    let name: String
    let description: String
    let updatedAt: Date

    var body: some View {
        HStack(spacing: 14) {
            // Coloured icon badge
            ZStack {
                RoundedRectangle(cornerRadius: 10, style: .continuous)
                    .fill(iconColor.opacity(0.12))
                    .frame(width: 40, height: 40)
                Image(systemName: icon)
                    .font(.system(size: 17, weight: .medium))
                    .foregroundStyle(iconColor)
            }
            .accessibilityHidden(true)

            VStack(alignment: .leading, spacing: 3) {
                Text(name)
                    .font(.body.weight(.semibold))
                    .foregroundStyle(.primary)
                    .lineLimit(2)

                if !description.isEmpty {
                    Text(description)
                        .font(.subheadline)
                        .foregroundStyle(.secondary)
                        .lineLimit(1)
                }

                Text(String(format: L("library.updated"), updatedAt.bookStackRelative))
                    .font(.caption)
                    .foregroundStyle(.tertiary)
            }

            Spacer(minLength: 0)
        }
        .padding(.vertical, 6)
    }
}

#Preview("Library Row — Shelf") {
    NavigationStack {
        List {
            ContentRowView(icon: "books.vertical.fill", iconColor: AccentTheme.ocean.shelfColor,
                           name: "Engineering Docs",
                           description: "Internal technical documentation for all engineering teams",
                           updatedAt: Date())
            ContentRowView(icon: "books.vertical.fill", iconColor: AccentTheme.ocean.shelfColor,
                           name: "Project Alpha",
                           description: "Documentation for Project Alpha",
                           updatedAt: Date())
            ContentRowView(icon: "books.vertical.fill", iconColor: AccentTheme.ocean.shelfColor,
                           name: "HR Policies",
                           description: "",
                           updatedAt: Date())
        }
        .listStyle(.insetGrouped)
        .navigationTitle("Library")
    }
}

#Preview("Library") {
    LibraryView()
        .environment(ConnectivityMonitor.shared)
}
