import SwiftUI
import SwiftData

struct TagListView: View {
    @Query(sort: \Tag.sortOrder) private var tags: [Tag]
    @Query private var allSettings: [AppSettings]
    @State private var selectedTag: Tag?

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

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

            List {
                ForEach(tags) { tag in
                    Button {
                        selectedTag = tag
                    } label: {
                        HStack {
                            Circle()
                                .fill(Color(hex: tag.color))
                                .frame(width: 14, height: 14)

                            VStack(alignment: .leading, spacing: 2) {
                                Text(tag.localizedName(language: language))
                                    .font(.mealMoodBodyBold)
                                    .foregroundColor(.mealMoodTextPrimary)

                                Text(tag.localizedRulesDescription(language: language))
                                    .font(.mealMoodCaption)
                                    .foregroundColor(.mealMoodTextSecondary)
                            }

                            Spacer()

                            Image(systemName: "chevron.right")
                                .font(.system(size: 12))
                                .foregroundColor(.mealMoodTextSecondary)
                        }
                    }
                    .listRowBackground(Color.mealMoodSurface)
                }
            }
            .scrollContentBackground(.hidden)
        }
        .navigationTitle("tags_title")
        .sheet(item: $selectedTag) { tag in
            TagRulesEditView(tag: tag)
        }
    }
}
