import SwiftUI

struct MealSectionView: View {
    let group: MealGroup
    let isExpanded: Bool
    let onToggle: () -> Void
    let onDelete: (FoodEntry) -> Void
    let onAddFood: () -> Void

    @State private var selectedEntry: FoodEntry?

    private var mealColor: Color {
        Color.mealColor(for: group.meal.rawValue)
    }

    var body: some View {
        VStack(spacing: 0) {
            // Header
            Button(action: onToggle) {
                HStack(spacing: 10) {
                    Image(systemName: group.meal.icon)
                        .font(.body)
                        .foregroundStyle(mealColor)
                        .frame(width: 28)

                    Text(group.meal.displayName)
                        .font(.subheadline.weight(.semibold))
                        .foregroundStyle(Color.text1)

                    if !group.entries.isEmpty {
                        Text("\(group.entries.count)")
                            .font(.caption2.weight(.bold))
                            .foregroundStyle(mealColor)
                            .padding(.horizontal, 6)
                            .padding(.vertical, 2)
                            .background(mealColor.opacity(0.1))
                            .clipShape(Capsule())
                    }

                    Spacer()

                    if !group.entries.isEmpty {
                        Text("\(Int(group.totalCalories)) kcal")
                            .font(.caption.weight(.semibold))
                            .foregroundStyle(Color.text3)
                    }

                    Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
                        .font(.caption.weight(.semibold))
                        .foregroundStyle(Color.text4)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 14)
            }
            .buttonStyle(.plain)

            // Entries
            if isExpanded {
                if group.entries.isEmpty {
                    emptyMealView
                } else {
                    Divider()
                        .padding(.horizontal, 16)

                    ForEach(group.entries) { entry in
                        SwipeToDeleteRow(onDelete: { onDelete(entry) }) {
                            EntryRow(entry: entry)
                                .contentShape(Rectangle())
                                .onTapGesture {
                                    selectedEntry = entry
                                }
                        }

                        if entry.id != group.entries.last?.id {
                            Divider()
                                .padding(.leading, 52)
                        }
                    }
                }
            }
        }
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 14))
        .shadow(color: .black.opacity(0.03), radius: 4, y: 2)
        .sheet(item: $selectedEntry) { entry in
            EntryDetailView(
                entry: entry,
                onDelete: { onDelete(entry) },
                onUpdateQuantity: { _ in }
            )
            .presentationDetents([.large])
        }
    }

    private var emptyMealView: some View {
        Button(action: onAddFood) {
            HStack(spacing: 8) {
                Image(systemName: "plus.circle")
                    .foregroundStyle(mealColor)
                Text("Add food")
                    .font(.subheadline)
                    .foregroundStyle(Color.text3)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 16)
        }
        .buttonStyle(.plain)
    }
}

// MARK: - Swipe to Delete Row

struct SwipeToDeleteRow<Content: View>: View {
    let onDelete: () -> Void
    @ViewBuilder let content: () -> Content

    @State private var offset: CGFloat = 0
    @State private var showDelete = false

    private let deleteThreshold: CGFloat = -80
    private let deleteWidth: CGFloat = 80

    var body: some View {
        ZStack(alignment: .trailing) {
            // Delete background
            HStack {
                Spacer()
                Button(action: {
                    withAnimation(.easeOut(duration: 0.2)) {
                        offset = -300
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                        onDelete()
                    }
                }) {
                    Image(systemName: "trash.fill")
                        .foregroundStyle(.white)
                        .frame(width: deleteWidth, height: .infinity)
                }
                .frame(width: deleteWidth)
                .background(Color.error)
            }
            .opacity(offset < 0 ? 1 : 0)

            // Content
            content()
                .offset(x: offset)
                .gesture(
                    DragGesture(minimumDistance: 20)
                        .onChanged { value in
                            let translation = value.translation.width
                            if translation < 0 {
                                offset = translation
                            }
                        }
                        .onEnded { value in
                            withAnimation(.easeOut(duration: 0.2)) {
                                if offset < deleteThreshold {
                                    offset = -deleteWidth
                                    showDelete = true
                                } else {
                                    offset = 0
                                    showDelete = false
                                }
                            }
                        }
                )
                .onTapGesture {
                    if showDelete {
                        withAnimation(.easeOut(duration: 0.2)) {
                            offset = 0
                            showDelete = false
                        }
                    }
                }
        }
        .clipped()
    }
}

// MARK: - Entry Row

struct EntryRow: View {
    let entry: FoodEntry

    var body: some View {
        HStack(spacing: 12) {
            // Food icon or image
            ZStack {
                Circle()
                    .fill(Color.mealColor(for: entry.mealType).opacity(0.1))
                    .frame(width: 36, height: 36)

                if let imageUrl = entry.imageUrl, !imageUrl.isEmpty {
                    AsyncImage(url: URL(string: imageUrl)) { image in
                        image
                            .resizable()
                            .scaledToFill()
                            .frame(width: 36, height: 36)
                            .clipShape(Circle())
                    } placeholder: {
                        Image(systemName: "fork.knife")
                            .font(.caption)
                            .foregroundStyle(Color.mealColor(for: entry.mealType))
                    }
                } else {
                    Image(systemName: "fork.knife")
                        .font(.caption)
                        .foregroundStyle(Color.mealColor(for: entry.mealType))
                }
            }

            // Name and serving
            VStack(alignment: .leading, spacing: 2) {
                Text(entry.foodName)
                    .font(.subheadline.weight(.medium))
                    .foregroundStyle(Color.text1)
                    .lineLimit(1)

                Text(entry.servingDescription ?? "\(formatQuantity(entry.quantity)) \(entry.unit)")
                    .font(.caption)
                    .foregroundStyle(Color.text3)
                    .lineLimit(1)
            }

            Spacer()

            // Macros
            VStack(alignment: .trailing, spacing: 2) {
                Text("\(Int(entry.calories))")
                    .font(.subheadline.weight(.bold))
                    .foregroundStyle(Color.text1)
                + Text(" kcal")
                    .font(.caption2)
                    .foregroundStyle(Color.text3)

                HStack(spacing: 6) {
                    macroTag("P", value: entry.protein, color: .proteinColor)
                    macroTag("C", value: entry.carbs, color: .carbsColor)
                    macroTag("F", value: entry.fat, color: .fatColor)
                }
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
        .background(Color.surface)
    }

    private func macroTag(_ label: String, value: Double, color: Color) -> some View {
        Text("\(label)\(Int(value))")
            .font(.system(size: 10, weight: .semibold))
            .foregroundStyle(color)
    }

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