import SwiftUI
import SwiftData

struct DishListView: View {
    @Environment(\.modelContext) private var context
    @Query(sort: \Dish.createdAt, order: .reverse) private var dishes: [Dish]
    @Query private var tags: [Tag]
    @Query private var allSettings: [AppSettings]
    @Query private var weekPlans: [WeekPlan]
    @State private var showDishForm = false
    @State private var editingDish: Dish?
    @State private var showDeleteBlockedAlert = false

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

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

            if dishes.isEmpty {
                VStack(spacing: 16) {
                    Image(systemName: "fork.knife")
                        .font(.system(size: 50))
                        .foregroundColor(Color(hex: "#C4C4C4"))
                    Text("dish_list_empty")
                        .font(.mealMoodBody)
                        .foregroundColor(.mealMoodTextSecondary)
                    PrimaryButton(title: String(localized: "home_add_dish"), action: { showDishForm = true })
                        .padding(.horizontal, 60)
                }
            } else {
                List {
                    ForEach(dishes) { dish in
                        let dishTags = tags.filter { dish.tagIds.contains($0.id) }
                        Button {
                            editingDish = dish
                        } label: {
                            HStack {
                                VStack(alignment: .leading, spacing: 4) {
                                    Text(dish.name)
                                        .font(.mealMoodBodyBold)
                                        .foregroundColor(.mealMoodTextPrimary)
                                    if let desc = dish.descriptionText, !desc.isEmpty {
                                        Text(desc)
                                            .font(.mealMoodCaption)
                                            .foregroundColor(.mealMoodTextSecondary)
                                            .lineLimit(1)
                                    }
                                }
                                Spacer()
                                HStack(spacing: 4) {
                                    ForEach(dishTags.prefix(2)) { tag in
                                        TagPill(name: tag.localizedName(language: language), color: tag.color)
                                    }
                                }
                                Image(systemName: "chevron.right")
                                    .font(.system(size: 12))
                                    .foregroundColor(.mealMoodTextSecondary)
                            }
                        }
                        .listRowBackground(Color.mealMoodSurface)
                    }
                    .onDelete(perform: deleteDishes)
                }
                .scrollContentBackground(.hidden)
            }
        }
        .navigationTitle("home_my_dishes")
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button {
                    showDishForm = true
                } label: {
                    Image(systemName: "plus")
                        .foregroundColor(.mealMoodCoral)
                }
            }
        }
        .sheet(isPresented: $showDishForm) {
            DishFormView()
        }
        .sheet(item: $editingDish) { dish in
            DishFormView(dish: dish)
        }
        .alert("dish_delete_blocked_title", isPresented: $showDeleteBlockedAlert) {
            Button("dish_delete_blocked_ok", role: .cancel) {}
        } message: {
            Text("dish_delete_blocked_message")
        }
    }

    private func deleteDishes(at offsets: IndexSet) {
        let currentWeekStart = Date().startOfWeek()
        let currentWeekPlan = weekPlans.first { $0.weekStartDate == currentWeekStart }

        for index in offsets {
            let dish = dishes[index]
            if currentWeekPlan?.slots.contains(where: { $0.dishId == dish.id }) == true {
                showDeleteBlockedAlert = true
                continue
            }
            context.delete(dish)
        }
        try? context.save()
    }
}
