import SwiftUI

struct EntryDetailView: View {
    let entry: FoodEntry
    let onDelete: () -> Void
    let onUpdateQuantity: (Double) -> Void

    @Environment(\.dismiss) private var dismiss
    @State private var editQuantity: String
    @State private var showDeleteConfirm = false

    init(entry: FoodEntry, onDelete: @escaping () -> Void, onUpdateQuantity: @escaping (Double) -> Void) {
        self.entry = entry
        self.onDelete = onDelete
        self.onUpdateQuantity = onUpdateQuantity
        _editQuantity = State(initialValue: entry.quantity == entry.quantity.rounded() ? "\(Int(entry.quantity))" : String(format: "%.1f", entry.quantity))
    }

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 20) {
                    // Header
                    entryHeader

                    // Quantity editor
                    quantityEditor

                    // Macros grid
                    macrosGrid

                    // Details
                    detailsSection

                    // Delete button
                    Button(role: .destructive) {
                        showDeleteConfirm = true
                    } label: {
                        HStack(spacing: 8) {
                            Image(systemName: "trash")
                            Text("Delete Entry")
                        }
                        .font(.body.weight(.medium))
                        .foregroundStyle(Color.error)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 14)
                        .background(Color.error.opacity(0.06))
                        .clipShape(RoundedRectangle(cornerRadius: 12))
                    }
                }
                .padding(20)
            }
            .background(Color.canvas)
            .navigationTitle("Entry Details")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("Done") {
                        dismiss()
                    }
                    .foregroundStyle(Color.accentWarm)
                }
            }
            .confirmationDialog("Delete Entry", isPresented: $showDeleteConfirm) {
                Button("Delete", role: .destructive) {
                    onDelete()
                    dismiss()
                }
                Button("Cancel", role: .cancel) {}
            } message: {
                Text("Are you sure you want to delete \"\(entry.foodName)\"?")
            }
        }
    }

    private var entryHeader: some View {
        VStack(spacing: 12) {
            ZStack {
                Circle()
                    .fill(Color.mealColor(for: entry.mealType).opacity(0.1))
                    .frame(width: 64, height: 64)

                Image(systemName: Color.mealIcon(for: entry.mealType))
                    .font(.title2)
                    .foregroundStyle(Color.mealColor(for: entry.mealType))
            }

            Text(entry.foodName)
                .font(.title3.weight(.semibold))
                .foregroundStyle(Color.text1)
                .multilineTextAlignment(.center)

            Text(entry.mealType.capitalized)
                .font(.caption.weight(.semibold))
                .foregroundStyle(Color.mealColor(for: entry.mealType))
                .padding(.horizontal, 12)
                .padding(.vertical, 4)
                .background(Color.mealColor(for: entry.mealType).opacity(0.1))
                .clipShape(Capsule())
        }
    }

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

            HStack(spacing: 12) {
                Button {
                    let current = Double(editQuantity) ?? 1
                    let newVal = max(0.5, current - 0.5)
                    editQuantity = formatQuantity(newVal)
                } label: {
                    Image(systemName: "minus.circle.fill")
                        .font(.title2)
                        .foregroundStyle(Color.accentWarm)
                }

                TextField("1", text: $editQuantity)
                    .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))

                Button {
                    let current = Double(editQuantity) ?? 1
                    editQuantity = formatQuantity(current + 0.5)
                } label: {
                    Image(systemName: "plus.circle.fill")
                        .font(.title2)
                        .foregroundStyle(Color.accentWarm)
                }

                Spacer()

                Button("Save") {
                    if let qty = Double(editQuantity), qty > 0 {
                        onUpdateQuantity(qty)
                        dismiss()
                    }
                }
                .font(.subheadline.weight(.semibold))
                .foregroundStyle(.white)
                .padding(.horizontal, 16)
                .padding(.vertical, 8)
                .background(Color.accentWarm)
                .clipShape(Capsule())
            }
        }
        .padding(16)
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 14))
    }

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

            LazyVGrid(columns: [
                GridItem(.flexible()),
                GridItem(.flexible()),
                GridItem(.flexible())
            ], spacing: 12) {
                macroCell("Calories", value: entry.calories, unit: "kcal", color: .caloriesColor)
                macroCell("Protein", value: entry.protein, unit: "g", color: .proteinColor)
                macroCell("Carbs", value: entry.carbs, unit: "g", color: .carbsColor)
                macroCell("Fat", value: entry.fat, unit: "g", color: .fatColor)
                if let sugar = entry.sugar {
                    macroCell("Sugar", value: sugar, unit: "g", color: .sugarColor)
                }
                if let fiber = entry.fiber {
                    macroCell("Fiber", value: fiber, unit: "g", color: .fiberColor)
                }
            }
        }
        .padding(16)
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 14))
    }

    private func macroCell(_ label: String, value: Double, unit: String, color: Color) -> some View {
        VStack(spacing: 4) {
            Text("\(Int(value))")
                .font(.title3.weight(.bold))
                .foregroundStyle(color)
            Text(label)
                .font(.caption2)
                .foregroundStyle(Color.text3)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 10)
        .background(color.opacity(0.06))
        .clipShape(RoundedRectangle(cornerRadius: 10))
    }

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

            VStack(spacing: 0) {
                detailRow("Serving", value: entry.servingDescription ?? "\(formatQuantity(entry.quantity)) \(entry.unit)")

                if let method = entry.method, !method.isEmpty {
                    Divider()
                    detailRow("Method", value: method)
                }

                if let note = entry.note, !note.isEmpty {
                    Divider()
                    detailRow("Note", value: note)
                }

                if let loggedAt = entry.loggedAt, !loggedAt.isEmpty {
                    Divider()
                    detailRow("Logged", value: loggedAt)
                }
            }
            .background(Color.surface)
            .clipShape(RoundedRectangle(cornerRadius: 14))
        }
    }

    private func detailRow(_ label: String, value: String) -> some View {
        HStack {
            Text(label)
                .font(.subheadline)
                .foregroundStyle(Color.text3)
            Spacer()
            Text(value)
                .font(.subheadline.weight(.medium))
                .foregroundStyle(Color.text1)
                .lineLimit(2)
                .multilineTextAlignment(.trailing)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

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