import SwiftUI

struct BookDetailView: View {
    let book: BookDTO
    var shelfName: String? = nil
    @State private var viewModel = LibraryViewModel()
    @State private var showNewPage = false
    @State private var showNewChapter = false
    @Environment(\.accentTheme) private var theme
    @Environment(\.dismiss) private var dismiss

    private var breadcrumbs: [Crumb] {
        if let shelf = shelfName {
            return [
                Crumb(label: L("library.title"), action: { dismiss() }),
                Crumb(label: shelf, action: { dismiss() }),
                Crumb(label: book.name, action: nil)
            ]
        }
        return [
            Crumb(label: L("library.title"), action: { dismiss() }),
            Crumb(label: book.name, action: nil)
        ]
    }

    var body: some View {
        Group {
            if viewModel.isLoadingContent && viewModel.chapters.isEmpty && viewModel.pages.isEmpty {
                LoadingView(message: L("book.loading"))
            } else if viewModel.chapters.isEmpty && viewModel.pages.isEmpty && viewModel.error == nil {
                EmptyStateView(
                    systemImage: "doc.text",
                    title: L("book.empty.title"),
                    message: L("book.empty.message"),
                    actionTitle: L("book.addpage"),
                    action: { showNewPage = true }
                )
            } else {
                List {
                    if let error = viewModel.error {
                        ErrorBanner(error: error) {
                            Task { await viewModel.loadChaptersAndPages(bookId: book.id) }
                        }
                        .listRowBackground(Color.clear)
                        .listRowSeparator(.hidden)
                    }

                    Section {
                        BreadcrumbBar(crumbs: breadcrumbs)
                            .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
                            .listRowBackground(Color.clear)
                            .listRowSeparator(.hidden)
                    }

                    // Chapters with their pages
                    ForEach(viewModel.chapters) { chapter in
                        Section {
                            ForEach(pagesInChapter(chapter.id)) { page in
                                NavigationLink(value: page) {
                                    ContentRowView(
                                        icon: "doc.text.fill",
                                        iconColor: theme.pageColor,
                                        name: page.name,
                                        description: "",
                                        updatedAt: page.updatedAt
                                    )
                                }
                                .accessibilityLabel("Page: \(page.name)")
                                .contextMenu { pageContextMenu(page) }
                                .swipeActions(edge: .trailing) {
                                    Button(role: .destructive) {
                                        Task { await viewModel.deletePage(id: page.id) }
                                    } label: {
                                        Label(L("book.delete"), systemImage: "trash")
                                    }
                                }
                            }
                        } header: {
                            HStack(spacing: 6) {
                                Image(systemName: "list.bullet.rectangle.fill")
                                    .font(.caption.weight(.semibold))
                                    .foregroundStyle(theme.bookColor)
                                Text(chapter.name)
                                    .font(.subheadline.weight(.semibold))
                                    .foregroundStyle(.primary)
                            }
                            .textCase(nil)
                        }
                    }

                    // Uncategorised pages
                    let uncategorised = pagesWithoutChapter
                    if !uncategorised.isEmpty {
                        Section {
                            ForEach(uncategorised) { page in
                                NavigationLink(value: page) {
                                    ContentRowView(
                                        icon: "doc.text.fill",
                                        iconColor: theme.pageColor,
                                        name: page.name,
                                        description: "",
                                        updatedAt: page.updatedAt
                                    )
                                }
                                .accessibilityLabel("Page: \(page.name)")
                                .contextMenu { pageContextMenu(page) }
                                .swipeActions(edge: .trailing) {
                                    Button(role: .destructive) {
                                        Task { await viewModel.deletePage(id: page.id) }
                                    } label: {
                                        Label(L("book.delete"), systemImage: "trash")
                                    }
                                }
                            }
                        } header: {
                            Text(L("book.pages"))
                                .font(.subheadline.weight(.semibold))
                                .foregroundStyle(.primary)
                                .textCase(nil)
                        }
                    }
                }
                .listStyle(.insetGrouped)
                .refreshable { await viewModel.loadChaptersAndPages(bookId: book.id) }
                .animation(.easeInOut, value: viewModel.pages.map(\.id))
            }
        }
        .navigationTitle(book.name)
        .navigationBarTitleDisplayMode(.large)
        .toolbar {
            ToolbarItem(placement: .primaryAction) {
                Menu {
                    Button { showNewPage = true } label: {
                        Label(L("book.newpage"), systemImage: "doc.text.badge.plus")
                    }
                    Button { showNewChapter = true } label: {
                        Label(L("book.newchapter"), systemImage: "list.bullet.rectangle.portrait.badge.plus")
                    }
                } label: {
                    Image(systemName: "plus")
                }
                .accessibilityLabel("Add content")
            }
        }
        .fullScreenCover(isPresented: $showNewPage) {
            NavigationStack { PageEditorView(mode: .create(bookId: book.id)) }
        }
        .sheet(isPresented: $showNewChapter) {
            NewChapterView(bookId: book.id)
        }
        .task { await viewModel.loadChaptersAndPages(bookId: book.id) }
        .onChange(of: showNewPage) { _, isShowing in
            if !isShowing { Task { await viewModel.loadChaptersAndPages(bookId: book.id) } }
        }
        .onChange(of: showNewChapter) { _, isShowing in
            if !isShowing { Task { await viewModel.loadChaptersAndPages(bookId: book.id) } }
        }
    }

    private func pagesInChapter(_ chapterId: Int) -> [PageDTO] {
        viewModel.pages.filter { $0.chapterId == chapterId }
            .sorted { $0.priority < $1.priority }
    }

    private var pagesWithoutChapter: [PageDTO] {
        viewModel.pages.filter { $0.chapterId == nil }
            .sorted { $0.priority < $1.priority }
    }

    @ViewBuilder
    private func pageContextMenu(_ page: PageDTO) -> some View {
        NavigationLink(value: page) {
            Label(L("book.open"), systemImage: "arrow.up.right.square")
        }
        Button {
            let url = "\(UserDefaults.standard.string(forKey: "serverURL") ?? "")/books/\(book.slug)/page/\(page.slug)"
            let activity = UIActivityViewController(activityItems: [url], applicationActivities: nil)
            if let window = UIApplication.shared.connectedScenes
                .compactMap({ $0 as? UIWindowScene })
                .first?.keyWindow {
                window.rootViewController?.present(activity, animated: true)
            }
        } label: {
            Label(L("book.sharelink"), systemImage: "square.and.arrow.up")
        }
        Divider()
        Button(role: .destructive) {
            Task { await viewModel.deletePage(id: page.id) }
        } label: {
            Label(L("book.delete"), systemImage: "trash")
        }
    }
}

// MARK: - New Chapter sheet

struct NewChapterView: View {
    let bookId: Int
    @State private var name = ""
    @State private var chapterDescription = ""
    @State private var isSaving = false
    @State private var error: BookStackError?
    @Environment(\.dismiss) private var dismiss

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

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

#Preview("Book Detail") {
    NavigationStack {
        List {
            Section {
                ForEach(PageDTO.mockList.filter { $0.chapterId == 1 }) { page in
                    ContentRowView(
                        icon: "doc.text.fill",
                        iconColor: AccentTheme.ocean.pageColor,
                        name: page.name,
                        description: "",
                        updatedAt: page.updatedAt
                    )
                }
            } header: {
                HStack(spacing: 6) {
                    Image(systemName: "list.bullet.rectangle.fill")
                        .font(.caption.weight(.semibold))
                        .foregroundStyle(AccentTheme.ocean.bookColor)
                    Text("Getting Started")
                        .font(.subheadline.weight(.semibold))
                        .foregroundStyle(.primary)
                }
                .textCase(nil)
            }

            Section {
                ForEach(PageDTO.mockList.filter { $0.chapterId == nil }) { page in
                    ContentRowView(
                        icon: "doc.text.fill",
                        iconColor: AccentTheme.ocean.pageColor,
                        name: page.name,
                        description: "",
                        updatedAt: page.updatedAt
                    )
                }
            } header: {
                Text("Pages")
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(.primary)
                    .textCase(nil)
            }
        }
        .listStyle(.insetGrouped)
        .navigationTitle("iOS Development Guide")
    }
}
