import SwiftUI

struct AddFoodSheet: View {
    let food: FoodItem
    @Binding var quantity: Double
    @Binding var mealType: MealType
    let isAdding: Bool
    let onAdd: () -> Void

    @Environment(\.dismiss) private var dismiss
    @State private var quantityText: String = "1"

    var body: some View {
        NavigationStack {
            VStack(spacing: 24) {
                // Food info header
                foodHeader

                // Quantity input
                quantitySection

                // Meal picker
                mealPickerSection

                // Macro preview
                macroPreview

                Spacer()

                // Add button
                Button(action: onAdd) {
                    HStack(spacing: 8) {
                        if isAdding {
                            ProgressView()
                                .controlSize(.small)
                                .tint(.white)
                        }
                        Text("Add to \(mealType.displayName)")
                            .font(.body.weight(.semibold))
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 16)
                    .background(Color.accentWarm)
                    .foregroundStyle(.white)
                    .clipShape(RoundedRectangle(cornerRadius: 14))
                }
                .disabled(isAdding || quantity <= 0)
            }
            .padding(20)
            .background(Color.canvas)
            .navigationTitle("Add Food")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button("Cancel") {
                        dismiss()
                    }
                    .foregroundStyle(Color.text3)
                }
            }
            .onAppear {
                quantityText = formatQuantity(quantity)
            }
        }
    }

    private var foodHeader: some View {
        HStack(spacing: 14) {
            ZStack {
                RoundedRectangle(cornerRadius: 12)
                    .fill(Color.accentWarmBg)
                    .frame(width: 48, height: 48)

                Image(systemName: "fork.knife")
                    .foregroundStyle(Color.accentWarm)
            }

            VStack(alignment: .leading, spacing: 2) {
                Text(food.name)
                    .font(.headline)
                    .foregroundStyle(Color.text1)
                    .lineLimit(2)

                Text("\(Int(food.caloriesPerBase)) kcal per \(food.displayUnit)")
                    .font(.caption)
                    .foregroundStyle(Color.text3)
            }

            Spacer()
        }
    }

    private var quantitySection: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("Quantity (\(food.displayUnit))")
                .font(.caption.weight(.semibold))
                .foregroundStyle(Color.text3)
                .textCase(.uppercase)

            HStack(spacing: 12) {
                // Decrement
                Button {
                    adjustQuantity(by: -0.5)
                } label: {
                    Image(systemName: "minus.circle.fill")
                        .font(.title2)
                        .foregroundStyle(quantity > 0.5 ? Color.accentWarm : Color.text4)
                }
                .disabled(quantity <= 0.5)

                // Text field
                TextField("1", text: $quantityText)
                    .textFieldStyle(.plain)
                    .keyboardType(.decimalPad)
                    .multilineTextAlignment(.center)
                    .font(.title2.weight(.bold))
                    .foregroundStyle(Color.text1)
                    .frame(width: 80)
                    .padding(.vertical, 8)
                    .background(Color.surface)
                    .clipShape(RoundedRectangle(cornerRadius: 10))
                    .overlay(
                        RoundedRectangle(cornerRadius: 10)
                            .stroke(Color.black.opacity(0.06), lineWidth: 1)
                    )
                    .onChange(of: quantityText) {
                        if let val = Double(quantityText), val > 0 {
                            quantity = val
                        }
                    }

                // Increment
                Button {
                    adjustQuantity(by: 0.5)
                } label: {
                    Image(systemName: "plus.circle.fill")
                        .font(.title2)
                        .foregroundStyle(Color.accentWarm)
                }

                Spacer()

                // Quick presets
                ForEach([0.5, 1.0, 2.0], id: \.self) { preset in
                    Button {
                        quantity = preset
                        quantityText = formatQuantity(preset)
                    } label: {
                        Text(formatQuantity(preset))
                            .font(.caption.weight(.semibold))
                            .foregroundStyle(quantity == preset ? .white : Color.text2)
                            .padding(.horizontal, 12)
                            .padding(.vertical, 6)
                            .background(quantity == preset ? Color.accentWarm : Color.surfaceSecondary)
                            .clipShape(Capsule())
                    }
                }
            }
        }
    }

    private var mealPickerSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("Meal")
                .font(.caption.weight(.semibold))
                .foregroundStyle(Color.text3)
                .textCase(.uppercase)

            HStack(spacing: 8) {
                ForEach(MealType.allCases) { meal in
                    Button {
                        mealType = meal
                    } label: {
                        VStack(spacing: 4) {
                            Image(systemName: meal.icon)
                                .font(.body)
                            Text(meal.displayName)
                                .font(.caption2.weight(.medium))
                        }
                        .foregroundStyle(mealType == meal ? .white : Color.text2)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 10)
                        .background(
                            mealType == meal
                                ? Color.mealColor(for: meal.rawValue)
                                : Color.surfaceSecondary
                        )
                        .clipShape(RoundedRectangle(cornerRadius: 10))
                    }
                }
            }
        }
    }

    private var macroPreview: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("Nutrition Preview")
                .font(.caption.weight(.semibold))
                .foregroundStyle(Color.text3)
                .textCase(.uppercase)

            HStack(spacing: 0) {
                macroPreviewItem("Calories", value: food.scaledCalories(quantity: quantity), unit: "kcal", color: .caloriesColor)
                Spacer()
                macroPreviewItem("Protein", value: food.scaledProtein(quantity: quantity), unit: "g", color: .proteinColor)
                Spacer()
                macroPreviewItem("Carbs", value: food.scaledCarbs(quantity: quantity), unit: "g", color: .carbsColor)
                Spacer()
                macroPreviewItem("Fat", value: food.scaledFat(quantity: quantity), unit: "g", color: .fatColor)
            }
            .padding(16)
            .background(Color.surface)
            .clipShape(RoundedRectangle(cornerRadius: 12))
        }
    }

    private func macroPreviewItem(_ label: String, value: Double, unit: String, color: Color) -> some View {
        VStack(spacing: 4) {
            Text("\(Int(value))")
                .font(.system(.title3, design: .rounded, weight: .bold))
                .foregroundStyle(color)
            Text(label)
                .font(.caption2)
                .foregroundStyle(Color.text3)
        }
    }

    private func adjustQuantity(by amount: Double) {
        quantity = max(0.5, quantity + amount)
        quantityText = formatQuantity(quantity)
    }

    private func formatQuantity(_ qty: Double) -> String {
        if qty == qty.rounded() {
            return "\(Int(qty))"
        }
        return String(format: "%.1f", qty)
    }
}
