import SwiftUI

struct MealSectionView: View {
    let mealType: MealType
    let entries: [FoodEntry]
    let onDelete: (FoodEntry) -> Void

    @State private var isExpanded = true

    private var totalCalories: Double {
        entries.reduce(0) { $0 + $1.calories }
    }

    var body: some View {
        VStack(spacing: 0) {
            // Header
            Button {
                withAnimation(.easeInOut(duration: 0.2)) {
                    isExpanded.toggle()
                }
            } label: {
                HStack(spacing: 0) {
                    // Colored accent bar
                    RoundedRectangle(cornerRadius: 2)
                        .fill(Color.mealColor(for: mealType.rawValue))
                        .frame(width: 4, height: 40)
                        .padding(.trailing, 12)

                    // Meal icon in tinted circle
                    Image(systemName: mealType.icon)
                        .font(.title3.weight(.semibold))
                        .foregroundStyle(Color.mealColor(for: mealType.rawValue))
                        .frame(width: 32, height: 32)
                        .background(Color.mealColor(for: mealType.rawValue).opacity(0.12))
                        .clipShape(Circle())
                        .padding(.trailing, 10)

                    VStack(alignment: .leading, spacing: 2) {
                        Text(mealType.displayName)
                            .font(.title3.weight(.bold))
                            .foregroundStyle(Color.textPrimary)

                        Text("\(entries.count) item\(entries.count == 1 ? "" : "s")")
                            .font(.caption)
                            .foregroundStyle(Color.textTertiary)
                    }

                    Spacer()

                    Text("\(Int(totalCalories))")
                        .font(.title3.weight(.bold))
                        .foregroundStyle(Color.mealColor(for: mealType.rawValue))
                    + Text(" kcal")
                        .font(.caption.weight(.medium))
                        .foregroundStyle(Color.textSecondary)

                    Image(systemName: "chevron.right")
                        .font(.caption.weight(.medium))
                        .foregroundStyle(Color.textTertiary)
                        .rotationEffect(.degrees(isExpanded ? 90 : 0))
                        .padding(.leading, 8)
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 14)
                .background(Color.mealColor(for: mealType.rawValue).opacity(0.04))
                .clipShape(RoundedRectangle(cornerRadius: 14))
            }

            if isExpanded {
                ForEach(entries) { entry in
                    SwipeToDeleteRow(
                        onDelete: { onDelete(entry) },
                        onTap: { /* handled by NavigationLink */ },
                        destination: { EntryDetailView(entry: entry, onDelete: { onDelete(entry) }) }
                    ) {
                        entryRow(entry)
                    }
                }
            }
        }
        .background(Color.surfaceCard)
        .clipShape(RoundedRectangle(cornerRadius: 14))
        .shadow(color: .black.opacity(0.04), radius: 6, y: 2)
        .padding(.horizontal)
    }

    private func entryRow(_ entry: FoodEntry) -> some View {
        HStack {
            VStack(alignment: .leading, spacing: 3) {
                Text(entry.foodName)
                    .font(.subheadline.weight(.medium))
                    .foregroundStyle(Color.textPrimary)
                    .lineLimit(1)

                if let desc = entry.servingDescription ?? entry.snapshotServingLabel {
                    Text(desc)
                        .font(.caption)
                        .foregroundStyle(Color.textTertiary)
                        .lineLimit(1)
                }
            }

            Spacer()

            Text("\(Int(entry.calories)) kcal")
                .font(.subheadline.weight(.medium))
                .foregroundStyle(Color.textSecondary)

            Image(systemName: "chevron.right")
                .font(.caption2)
                .foregroundStyle(Color.textTertiary)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
        .background(Color.surfaceCard)
    }
}

// MARK: - Swipe to Delete Row

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

    @State private var offset: CGFloat = 0
    @State private var isSwiping = false
    @State private var showDetail = false

    var body: some View {
        ZStack(alignment: .trailing) {
            // Delete button background
            HStack {
                Spacer()
                Button {
                    withAnimation(.easeInOut(duration: 0.2)) {
                        onDelete()
                        offset = 0
                        isSwiping = false
                    }
                } label: {
                    Image(systemName: "trash.fill")
                        .foregroundStyle(.white)
                        .frame(maxHeight: .infinity)
                        .frame(width: 70)
                }
                .background(Color.red)
            }

            // Content row
            content()
                .offset(x: offset)
                .navigationDestination(isPresented: $showDetail) {
                    destination()
                }
                .onTapGesture {
                    if !isSwiping {
                        showDetail = true
                    } else {
                        // Close swipe
                        withAnimation(.easeOut(duration: 0.2)) {
                            offset = 0
                            isSwiping = false
                        }
                    }
                }
                .highPriorityGesture(
                    DragGesture(minimumDistance: 15)
                        .onChanged { value in
                            if value.translation.width < 0 {
                                offset = max(value.translation.width, -80)
                            } else if isSwiping {
                                offset = min(value.translation.width - 70, 0)
                            }
                        }
                        .onEnded { value in
                            withAnimation(.easeOut(duration: 0.2)) {
                                if value.translation.width < -40 {
                                    offset = -70
                                    isSwiping = true
                                } else {
                                    offset = 0
                                    isSwiping = false
                                }
                            }
                        }
                )
        }
        .clipShape(Rectangle())
    }
}
