import SwiftData
import SwiftUI

/// Browse notes by tag — the manual-organization counterpart to the
/// automatic context ranking.
struct TagsView: View {
    @Query(sort: \NoteEntity.createdAt, order: .reverse) private var notes: [NoteEntity]

    var body: some View {
        NavigationStack {
            List {
                ForEach(tagCounts, id: \.tag) { entry in
                    NavigationLink(value: entry.tag) {
                        HStack {
                            Label(entry.tag, systemImage: "tag")
                            Spacer()
                            Text("\(entry.count)")
                                .foregroundStyle(.secondary)
                                .monospacedDigit()
                        }
                    }
                }
            }
            .navigationTitle("Tags")
            .navigationDestination(for: String.self) { tag in
                TaggedNotesView(tag: tag)
            }
            .overlay {
                if tagCounts.isEmpty {
                    ContentUnavailableView(
                        "No tags yet",
                        systemImage: "tag",
                        description: Text("Add tags when writing a note to organize by topic.")
                    )
                }
            }
        }
    }

    private var tagCounts: [(tag: String, count: Int)] {
        var counts: [String: Int] = [:]
        for note in notes where note.isLive {
            for tag in note.tags {
                counts[tag, default: 0] += 1
            }
        }
        return counts
            .map { (tag: $0.key, count: $0.value) }
            .sorted { $0.count == $1.count ? $0.tag < $1.tag : $0.count > $1.count }
    }
}

struct TaggedNotesView: View {
    let tag: String

    @Query(sort: \NoteEntity.createdAt, order: .reverse) private var notes: [NoteEntity]
    @State private var editingNote: NoteEntity?

    var body: some View {
        List {
            ForEach(notes.filter { $0.isLive && $0.tags.contains(tag) }) { note in
                Button {
                    editingNote = note
                } label: {
                    NoteRowView(note: note)
                }
                .buttonStyle(.plain)
            }
        }
        .navigationTitle("#\(tag)")
        .sheet(item: $editingNote) { note in
            NoteEditorView(mode: .edit(note))
        }
    }
}
