import SwiftUI
import SwiftData

struct TagSelectorSheet: View {
    @Environment(\.modelContext) private var context
    let tags: [Tag]
    @Query(sort: \Tag.sortOrder) private var storedTags: [Tag]
    @Binding var selectedTagIds: Set<UUID>
    @Environment(\.dismiss) private var dismiss
    @Query private var allSettings: [AppSettings]

    private var language: AppLanguage {
        (allSettings.first?.languageEnum ?? .system).resolved()
    }

    private var displayedTags: [Tag] {
        let source = tags.isEmpty ? storedTags : tags
        return source.sorted(by: { $0.sortOrder < $1.sortOrder })
    }

    var body: some View {
        NavigationStack {
            ZStack {
                Color.mealMoodBackground.ignoresSafeArea()

                List {
                    ForEach(displayedTags) { tag in
                        Button {
                            if selectedTagIds.contains(tag.id) {
                                selectedTagIds.remove(tag.id)
                            } else {
                                selectedTagIds.insert(tag.id)
                            }
                            HapticManager.shared.selection()
                        } label: {
                            HStack {
                                Circle()
                                    .fill(Color(hex: tag.color))
                                    .frame(width: 12, height: 12)

                                Text(tag.localizedName(language: language))
                                    .font(.mealMoodBody)
                                    .foregroundColor(.mealMoodTextPrimary)

                                Spacer()

                                Image(systemName: selectedTagIds.contains(tag.id) ? "checkmark.circle.fill" : "circle")
                                    .foregroundColor(selectedTagIds.contains(tag.id) ? .mealMoodCoral : Color(hex: "#C4C4C4"))
                                    .font(.system(size: 22))
                            }
                        }
                        .listRowBackground(Color.mealMoodSurface)
                    }

                    if displayedTags.isEmpty {
                        Text("tag_selector_empty")
                            .font(.mealMoodSmall)
                            .foregroundColor(.mealMoodTextSecondary)
                            .listRowBackground(Color.mealMoodSurface)
                    }
                }
                .scrollContentBackground(.hidden)
            }
            .navigationTitle("tag_selector_title")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("tag_selector_done") { dismiss() }
                        .font(.mealMoodBodyBold)
                        .foregroundColor(.mealMoodCoral)
                }
            }
        }
        .onAppear {
            ensureDefaultTagsIfNeeded()
        }
    }

    private func ensureDefaultTagsIfNeeded() {
        let descriptor = FetchDescriptor<Tag>()
        if (try? context.fetch(descriptor))?.isEmpty ?? true {
            DefaultDataService.createDefaultTags(context: context)
        }
    }
}
