import SwiftUI

struct AddFoodSheet: View {
    @Environment(\.dismiss) private var dismiss
    let food: Food
    var onFoodAdded: (() -> Void)?

    @State private var quantity: Double = 1.0
    @State private var selectedMeal: MealType = .snack
    @State private var selectedServingId: String?
    @State private var entryDate = Date()
    @State private var isAdding = false
    @State private var error: String?

    private var defaultServing: FoodServing? {
        food.servings?.first(where: { $0.isDefault == 1 }) ?? food.servings?.first
    }

    private var multiplier: Double {
        if let servingId = selectedServingId,
           let serving = food.servings?.first(where: { $0.id == servingId }) {
            return quantity * serving.amountInBase
        }
        return quantity
    }

    private var previewCalories: Double { food.caloriesPerBase * multiplier }
    private var previewProtein: Double { food.proteinPerBase * multiplier }
    private var previewCarbs: Double { food.carbsPerBase * multiplier }
    private var previewFat: Double { food.fatPerBase * multiplier }

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 20) {
                    // Food name
                    VStack(spacing: 4) {
                        Text(food.name)
                            .font(.title3.weight(.semibold))
                            .foregroundStyle(Color.textPrimary)
                        if let brand = food.brand, !brand.isEmpty {
                            Text(brand)
                                .font(.subheadline)
                                .foregroundStyle(Color.textSecondary)
                        }
                        Text("Per \(food.baseUnit)")
                            .font(.caption)
                            .foregroundStyle(Color.textTertiary)
                    }
                    .frame(maxWidth: .infinity)
                    .padding()

                    // Quantity
                    VStack(alignment: .leading, spacing: 8) {
                        Text("Quantity")
                            .font(.subheadline.weight(.medium))
                            .foregroundStyle(Color.textSecondary)

                        HStack {
                            Button {
                                if quantity > 0.5 { quantity -= 0.5 }
                            } label: {
                                Image(systemName: "minus.circle.fill")
                                    .font(.title2)
                                    .foregroundStyle(Color.accentWarm)
                            }

                            Text(String(format: "%.1f", quantity))
                                .font(.title2.weight(.bold).monospacedDigit())
                                .foregroundStyle(Color.textPrimary)
                                .frame(minWidth: 60)

                            Button {
                                quantity += 0.5
                            } label: {
                                Image(systemName: "plus.circle.fill")
                                    .font(.title2)
                                    .foregroundStyle(Color.accentWarm)
                            }
                        }
                        .frame(maxWidth: .infinity)

                        // Serving picker
                        if let servings = food.servings, !servings.isEmpty {
                            Picker("Serving", selection: $selectedServingId) {
                                Text("Base (\(food.baseUnit))").tag(nil as String?)
                                ForEach(servings) { serving in
                                    Text(serving.name).tag(serving.id as String?)
                                }
                            }
                            .pickerStyle(.menu)
                        }
                    }
                    .padding()
                    .background(Color.surfaceCard)
                    .clipShape(RoundedRectangle(cornerRadius: 12))

                    // Meal picker
                    VStack(alignment: .leading, spacing: 8) {
                        Text("Meal")
                            .font(.subheadline.weight(.medium))
                            .foregroundStyle(Color.textSecondary)

                        HStack(spacing: 8) {
                            ForEach(MealType.allCases, id: \.rawValue) { meal in
                                Button {
                                    selectedMeal = meal
                                } label: {
                                    VStack(spacing: 4) {
                                        Image(systemName: meal.icon)
                                            .font(.body)
                                        Text(meal.displayName)
                                            .font(.caption2.weight(.medium))
                                    }
                                    .frame(maxWidth: .infinity)
                                    .padding(.vertical, 10)
                                    .background(selectedMeal == meal
                                        ? Color.mealColor(for: meal.rawValue).opacity(0.15)
                                        : Color.surfaceCard
                                    )
                                    .foregroundStyle(selectedMeal == meal
                                        ? Color.mealColor(for: meal.rawValue)
                                        : Color.textSecondary
                                    )
                                    .clipShape(RoundedRectangle(cornerRadius: 10))
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 10)
                                            .stroke(selectedMeal == meal
                                                ? Color.mealColor(for: meal.rawValue).opacity(0.3)
                                                : Color.clear, lineWidth: 1
                                            )
                                    )
                                }
                            }
                        }
                    }
                    .padding()
                    .background(Color.surfaceCard)
                    .clipShape(RoundedRectangle(cornerRadius: 12))

                    // Nutrition preview
                    VStack(spacing: 8) {
                        Text("Nutrition Preview")
                            .font(.subheadline.weight(.medium))
                            .foregroundStyle(Color.textSecondary)

                        LazyVGrid(columns: [
                            GridItem(.flexible()),
                            GridItem(.flexible()),
                            GridItem(.flexible()),
                            GridItem(.flexible()),
                        ], spacing: 12) {
                            nutritionCell("Calories", value: previewCalories, unit: "kcal", color: .emerald)
                            nutritionCell("Protein", value: previewProtein, unit: "g", color: .macroProtein)
                            nutritionCell("Carbs", value: previewCarbs, unit: "g", color: .macroCarbs)
                            nutritionCell("Fat", value: previewFat, unit: "g", color: .macroFat)
                        }
                    }
                    .padding()
                    .background(Color.surfaceCard)
                    .clipShape(RoundedRectangle(cornerRadius: 12))

                    if let error {
                        Text(error)
                            .font(.caption)
                            .foregroundStyle(.red)
                    }
                }
                .padding()
            }
            .scrollDismissesKeyboard(.immediately)
            .background(Color.canvas)
            .safeAreaInset(edge: .bottom) {
                Button {
                    addEntry()
                } label: {
                    if isAdding {
                        ProgressView()
                            .tint(.white)
                    } else {
                        Text("Add to \(selectedMeal.displayName)")
                            .font(.headline)
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(height: 50)
                .background(Color.accentWarm)
                .foregroundStyle(.white)
                .clipShape(RoundedRectangle(cornerRadius: 12))
                .disabled(isAdding)
                .padding(.horizontal)
                .padding(.bottom, 8)
                .background(Color.canvas)
            }
            .navigationTitle("Add Food")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
            }
        }
        .onAppear {
            if let ds = defaultServing {
                selectedServingId = ds.id
            }
        }
    }

    private func nutritionCell(_ label: String, value: Double, unit: String, color: Color) -> some View {
        VStack(spacing: 4) {
            Text("\(Int(value))")
                .font(.headline.monospacedDigit())
                .foregroundStyle(color)
            Text("\(unit)")
                .font(.caption2)
                .foregroundStyle(Color.textTertiary)
            Text(label)
                .font(.caption2.weight(.medium))
                .foregroundStyle(Color.textSecondary)
        }
        .frame(maxWidth: .infinity)
    }

    private func addEntry() {
        isAdding = true
        error = nil
        Task {
            do {
                let request = CreateEntryRequest(
                    foodId: food.id,
                    quantity: quantity,
                    unit: food.baseUnit,
                    mealType: selectedMeal.rawValue,
                    entryDate: entryDate.apiDateString,
                    entryMethod: "manual",
                    source: "ios",
                    servingId: selectedServingId
                )
                _ = try await FitnessRepository.shared.createEntry(request)
                dismiss()
                onFoodAdded?()
            } catch {
                self.error = error.localizedDescription
            }
            isAdding = false
        }
    }
}
