import SwiftUI

struct QuickNoteView: View {
    private let navState = AppNavigationState.shared

    // Form fields
    @State private var title = ""
    @State private var content = ""

    // Tag selection
    @State private var availableTags: [TagDTO] = []
    @State private var selectedTags: [TagDTO] = []
    @State private var isLoadingTags = false
    @State private var showTagPicker = false

    // Location selection
    @State private var shelves: [ShelfDTO] = []
    @State private var books: [BookDTO] = []
    @State private var selectedShelf: ShelfDTO? = nil
    @State private var selectedBook: BookDTO? = nil
    @State private var isLoadingShelves = false
    @State private var isLoadingBooks = false

    // Save state
    @State private var isSaving = false
    @State private var error: String? = nil

    var body: some View {
        NavigationStack {
            Form {
                // Note content
                Section(L("quicknote.field.title")) {
                    TextField(L("quicknote.field.title.placeholder"), text: $title)
                }

                Section(L("quicknote.field.content")) {
                    TextEditor(text: $content)
                        .frame(minHeight: 120)
                        .font(.system(.body, design: .monospaced))
                }

                // Location: shelf → book
                Section {
                    if isLoadingShelves {
                        HStack {
                            ProgressView().controlSize(.small)
                            Text(L("quicknote.shelf.loading"))
                                .foregroundStyle(.secondary)
                                .padding(.leading, 8)
                        }
                    } else {
                        Picker(L("quicknote.shelf.label"), selection: $selectedShelf) {
                            Text(L("quicknote.shelf.none")).tag(ShelfDTO?.none)
                            ForEach(shelves) { shelf in
                                Text(shelf.name).tag(ShelfDTO?.some(shelf))
                            }
                        }
                        .onChange(of: selectedShelf) { _, shelf in
                            selectedBook = nil
                            if let shelf {
                                Task { await loadBooks(for: shelf) }
                            } else {
                                Task { await loadAllBooks() }
                            }
                        }
                    }

                    if isLoadingBooks {
                        HStack {
                            ProgressView().controlSize(.small)
                            Text(L("quicknote.book.loading"))
                                .foregroundStyle(.secondary)
                                .padding(.leading, 8)
                        }
                    } else {
                        Picker(L("quicknote.book.label"), selection: $selectedBook) {
                            Text(L("quicknote.book.none")).tag(BookDTO?.none)
                            ForEach(books) { book in
                                Text(book.name).tag(BookDTO?.some(book))
                            }
                        }
                    }
                } header: {
                    Text(L("quicknote.section.location"))
                }

                // Tags section
                Section {
                    if isLoadingTags {
                        HStack {
                            ProgressView().controlSize(.small)
                            Text(L("quicknote.tags.loading"))
                                .foregroundStyle(.secondary)
                                .padding(.leading, 8)
                        }
                    } else {
                        if !selectedTags.isEmpty {
                            ScrollView(.horizontal, showsIndicators: false) {
                                HStack(spacing: 8) {
                                    ForEach(selectedTags) { tag in
                                        HStack(spacing: 4) {
                                            Text(tag.value.isEmpty ? tag.name : "\(tag.name): \(tag.value)")
                                                .font(.footnote)
                                                .foregroundStyle(.primary)
                                            Button {
                                                selectedTags.removeAll { $0.id == tag.id }
                                            } label: {
                                                Image(systemName: "xmark.circle.fill")
                                                    .foregroundStyle(.secondary)
                                                    .font(.footnote)
                                            }
                                            .buttonStyle(.plain)
                                        }
                                        .padding(.horizontal, 10)
                                        .padding(.vertical, 5)
                                        .background(Color.accentColor.opacity(0.12), in: Capsule())
                                        .overlay(Capsule().strokeBorder(Color.accentColor.opacity(0.3), lineWidth: 1))
                                    }
                                }
                                .padding(.vertical, 2)
                            }
                        }

                        Button {
                            showTagPicker = true
                        } label: {
                            Label(
                                selectedTags.isEmpty ? L("quicknote.tags.add") : L("quicknote.tags.edit"),
                                systemImage: "tag"
                            )
                            .foregroundStyle(Color.accentColor)
                        }
                    }
                } header: {
                    Text(L("quicknote.section.tags"))
                }

                // Error feedback
                if let err = error {
                    Section {
                        HStack {
                            Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.red)
                            Text(err).foregroundStyle(.red).font(.footnote)
                        }
                    }
                }
            }
            .navigationTitle(L("quicknote.title"))
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button(L("common.cancel")) {
                        resetForm()
                    }
                    .disabled(isSaving)
                }
                ToolbarItem(placement: .confirmationAction) {
                    if isSaving {
                        ProgressView().controlSize(.small)
                    } else {
                        Button(L("quicknote.save")) {
                            Task { await save() }
                        }
                        .disabled(title.isEmpty || selectedBook == nil)
                    }
                }
            }
            .task {
                await loadShelves()
                await loadTags()
            }
            .sheet(isPresented: $showTagPicker) {
                TagPickerSheet(
                    availableTags: availableTags,
                    selectedTags: $selectedTags
                )
            }
        }
    }

    // MARK: - Load shelves / books

    private func loadShelves() async {
        isLoadingShelves = true
        shelves = (try? await BookStackAPI.shared.fetchShelves()) ?? []
        isLoadingShelves = false
        await loadAllBooks()
    }

    private func loadAllBooks() async {
        isLoadingBooks = true
        books = (try? await BookStackAPI.shared.fetchBooks()) ?? []
        isLoadingBooks = false
    }

    private func loadBooks(for shelf: ShelfDTO) async {
        isLoadingBooks = true
        books = (try? await BookStackAPI.shared.fetchShelf(id: shelf.id))?.books ?? []
        isLoadingBooks = false
    }

    private func loadTags() async {
        isLoadingTags = true
        availableTags = (try? await BookStackAPI.shared.fetchTags()) ?? []
        isLoadingTags = false
    }

    // MARK: - Save

    private func save() async {
        guard let book = selectedBook else {
            error = L("quicknote.error.nobook")
            return
        }
        error = nil
        isSaving = true

        do {
            let page = try await BookStackAPI.shared.createPage(
                bookId: book.id,
                name: title,
                markdown: content,
                tags: selectedTags
            )
            AppLog(.info, "Quick note '\(title)' created as page \(page.id)", category: "QuickNote")
            resetForm()
            navState.pendingBookNavigation = book
        } catch {
            self.error = error.localizedDescription
        }

        isSaving = false
    }

    // MARK: - Helpers

    private func resetForm() {
        title = ""
        content = ""
        selectedTags = []
        selectedShelf = nil
        selectedBook = nil
    }
}

// MARK: - Tag Picker Sheet

struct TagPickerSheet: View {
    let availableTags: [TagDTO]
    @Binding var selectedTags: [TagDTO]
    @Environment(\.dismiss) private var dismiss
    @State private var searchText = ""

    private var filteredTags: [TagDTO] {
        guard !searchText.isEmpty else { return availableTags }
        return availableTags.filter {
            $0.name.localizedCaseInsensitiveContains(searchText) ||
            $0.value.localizedCaseInsensitiveContains(searchText)
        }
    }

    var body: some View {
        NavigationStack {
            List {
                if availableTags.isEmpty {
                    Text(L("quicknote.tags.empty"))
                        .foregroundStyle(.secondary)
                        .font(.subheadline)
                } else {
                    ForEach(filteredTags) { tag in
                        let isSelected = selectedTags.contains { $0.id == tag.id }
                        Button {
                            if isSelected {
                                selectedTags.removeAll { $0.id == tag.id }
                            } else {
                                selectedTags.append(tag)
                            }
                        } label: {
                            HStack {
                                VStack(alignment: .leading, spacing: 2) {
                                    Text(tag.name)
                                        .font(.body)
                                        .foregroundStyle(.primary)
                                    if !tag.value.isEmpty {
                                        Text(tag.value)
                                            .font(.caption)
                                            .foregroundStyle(.secondary)
                                    }
                                }
                                Spacer()
                                if isSelected {
                                    Image(systemName: "checkmark.circle.fill")
                                        .foregroundStyle(Color.accentColor)
                                }
                            }
                        }
                    }
                }
            }
            .navigationTitle(L("quicknote.tags.picker.title"))
            .navigationBarTitleDisplayMode(.inline)
            .searchable(text: $searchText, prompt: L("editor.tags.search"))
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button(L("common.done")) { dismiss() }
                }
            }
        }
    }
}
