import SwiftUI

struct EntryDetailView: View {
    let entry: FoodEntry
    let onDelete: () -> Void
    var onUpdate: (() -> Void)?
    @Environment(\.dismiss) private var dismiss
    @State private var showDeleteConfirmation = false
    @State private var editQuantity: String
    @State private var editMealType: MealType
    @State private var isSaving = false
    @State private var saveError: String?
    @State private var saveSuccess = false

    private let api = FitnessAPI()

    init(entry: FoodEntry, onDelete: @escaping () -> Void, onUpdate: (() -> Void)? = nil) {
        self.entry = entry
        self.onDelete = onDelete
        self.onUpdate = onUpdate
        _editQuantity = State(initialValue: String(format: "%.1f", entry.quantity))
        _editMealType = State(initialValue: MealType(rawValue: entry.mealType) ?? .snack)
    }

    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                // Header
                VStack(spacing: 6) {
                    Text(entry.foodName)
                        .font(.title2.weight(.bold))
                        .foregroundStyle(Color.textPrimary)
                        .multilineTextAlignment(.center)

                    if let desc = entry.servingDescription {
                        Text(desc)
                            .font(.subheadline)
                            .foregroundStyle(Color.textSecondary)
                    }
                }
                .frame(maxWidth: .infinity)
                .padding()

                // Editable fields
                VStack(spacing: 16) {
                    Text("Edit Entry")
                        .font(.headline)
                        .foregroundStyle(Color.textPrimary)
                        .frame(maxWidth: .infinity, alignment: .leading)

                    // Meal type picker
                    VStack(alignment: .leading, spacing: 8) {
                        Text("Meal")
                            .font(.subheadline.weight(.medium))
                            .foregroundStyle(Color.textSecondary)
                        Picker("Meal Type", selection: $editMealType) {
                            ForEach(MealType.allCases, id: \.self) { meal in
                                Label(meal.displayName, systemImage: meal.icon)
                                    .tag(meal)
                            }
                        }
                        .pickerStyle(.segmented)
                    }

                    // Quantity field
                    VStack(alignment: .leading, spacing: 8) {
                        Text("Quantity (\(entry.unit))")
                            .font(.subheadline.weight(.medium))
                            .foregroundStyle(Color.textSecondary)
                        HStack(spacing: 12) {
                            Button {
                                if let val = Double(editQuantity), val > 0.5 {
                                    editQuantity = String(format: "%.1f", val - 0.5)
                                }
                            } label: {
                                Image(systemName: "minus.circle.fill")
                                    .font(.title2)
                                    .foregroundStyle(Color.accentWarm)
                            }

                            TextField("1.0", text: $editQuantity)
                                .font(.title3.weight(.semibold).monospacedDigit())
                                .foregroundStyle(Color.textPrimary)
                                .multilineTextAlignment(.center)
                                .keyboardType(.decimalPad)
                                .frame(width: 80)
                                .padding(.vertical, 8)
                                .background(Color.canvas)
                                .clipShape(RoundedRectangle(cornerRadius: 8))

                            Button {
                                if let val = Double(editQuantity) {
                                    editQuantity = String(format: "%.1f", val + 0.5)
                                }
                            } label: {
                                Image(systemName: "plus.circle.fill")
                                    .font(.title2)
                                    .foregroundStyle(Color.accentWarm)
                            }
                        }
                        .frame(maxWidth: .infinity)
                    }

                    if saveSuccess {
                        HStack {
                            Image(systemName: "checkmark.circle.fill")
                                .foregroundStyle(Color.emerald)
                            Text("Entry updated")
                                .font(.caption.weight(.medium))
                                .foregroundStyle(Color.emerald)
                            Spacer()
                        }
                    }

                    if let error = saveError {
                        Text(error)
                            .font(.caption)
                            .foregroundStyle(.red)
                    }

                    Button {
                        Task { await saveChanges() }
                    } label: {
                        HStack {
                            if isSaving {
                                ProgressView()
                                    .controlSize(.small)
                                    .tint(.white)
                            }
                            Text("Save Changes")
                                .font(.subheadline.weight(.semibold))
                        }
                        .foregroundStyle(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 12)
                        .background(Color.emerald)
                        .clipShape(RoundedRectangle(cornerRadius: 10))
                    }
                    .disabled(isSaving)
                }
                .padding()
                .background(Color.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: 14))
                .shadow(color: .black.opacity(0.04), radius: 6, y: 2)

                // Nutrition grid
                LazyVGrid(columns: [
                    GridItem(.flexible()),
                    GridItem(.flexible()),
                    GridItem(.flexible()),
                ], spacing: 16) {
                    nutritionCell("Calories", value: entry.calories, unit: "kcal", color: .emerald)
                    nutritionCell("Protein", value: entry.protein, unit: "g", color: .macroProtein)
                    nutritionCell("Carbs", value: entry.carbs, unit: "g", color: .macroCarbs)
                    nutritionCell("Fat", value: entry.fat, unit: "g", color: .macroFat)
                    nutritionCell("Sugar", value: entry.sugar, unit: "g", color: .orange)
                    nutritionCell("Fiber", value: entry.fiber, unit: "g", color: .green)
                }
                .padding()
                .background(Color.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: 14))

                // Metadata
                VStack(spacing: 8) {
                    metadataRow("Date", value: entry.entryDate)
                    metadataRow("Source", value: entry.source)
                    metadataRow("Method", value: entry.entryMethod)
                    if let note = entry.note, !note.isEmpty {
                        metadataRow("Note", value: note)
                    }
                }
                .padding()
                .background(Color.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: 14))

                // Delete button
                Button(role: .destructive) {
                    showDeleteConfirmation = true
                } label: {
                    Label("Delete Entry", systemImage: "trash")
                        .font(.headline)
                        .frame(maxWidth: .infinity)
                        .frame(height: 48)
                }
                .buttonStyle(.borderedProminent)
                .tint(.red)
            }
            .padding()
        }
        .background(Color.canvas)
        .navigationTitle("Entry Detail")
        .navigationBarTitleDisplayMode(.inline)
        .alert("Delete Entry?", isPresented: $showDeleteConfirmation) {
            Button("Delete", role: .destructive) {
                onDelete()
                dismiss()
            }
            Button("Cancel", role: .cancel) {}
        } message: {
            Text("This will permanently remove \(entry.foodName) from your log.")
        }
    }

    private func saveChanges() async {
        isSaving = true
        saveError = nil
        saveSuccess = false
        do {
            let request = UpdateEntryRequest(
                quantity: Double(editQuantity),
                mealType: editMealType.rawValue
            )
            _ = try await api.updateEntry(id: entry.id, body: request)
            saveSuccess = true
            onUpdate?()
        } catch {
            saveError = error.localizedDescription
        }
        isSaving = false
    }

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

    private func metadataRow(_ label: String, value: String) -> some View {
        HStack {
            Text(label)
                .font(.subheadline)
                .foregroundStyle(Color.textSecondary)
            Spacer()
            Text(value)
                .font(.subheadline.weight(.medium))
                .foregroundStyle(Color.textPrimary)
        }
    }
}
