import SwiftUI

struct TodayView: View {
    @Bindable var viewModel: TodayViewModel
    @Binding var showFoodSearch: Bool

    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            ScrollView {
                VStack(spacing: 16) {
                    // Date selector
                    dateSelector

                    if viewModel.isLoading {
                        LoadingView(message: "Loading entries...")
                            .frame(height: 200)
                    } else {
                        // Macro summary card
                        macroSummaryCard

                        // Meal sections
                        ForEach(viewModel.mealGroups) { group in
                            MealSectionView(
                                group: group,
                                isExpanded: viewModel.expandedMeals.contains(group.meal.rawValue),
                                onToggle: { viewModel.toggleMeal(group.meal.rawValue) },
                                onDelete: { entry in
                                    Task { await viewModel.deleteEntry(entry) }
                                },
                                onAddFood: {
                                    showFoodSearch = true
                                }
                            )
                        }

                        // Bottom spacing for FAB
                        Spacer()
                            .frame(height: 80)
                    }

                    if let error = viewModel.errorMessage {
                        ErrorBanner(message: error) {
                            Task { await viewModel.load() }
                        }
                        .padding(.horizontal, 4)
                    }
                }
                .padding(16)
            }
            .refreshable {
                await viewModel.load()
            }

            // Floating add button
            addButton
        }
        .task {
            await viewModel.load()
        }
    }

    // MARK: - Date Selector

    private var dateSelector: some View {
        HStack(spacing: 0) {
            Button {
                viewModel.goToPreviousDay()
            } label: {
                Image(systemName: "chevron.left")
                    .font(.body.weight(.semibold))
                    .foregroundStyle(Color.accentWarm)
                    .frame(width: 44, height: 44)
            }

            Spacer()

            VStack(spacing: 2) {
                Text(viewModel.selectedDate.relativeLabel)
                    .font(.headline)
                    .foregroundStyle(Color.text1)
                if !viewModel.selectedDate.isToday {
                    Text(viewModel.selectedDate.displayString)
                        .font(.caption)
                        .foregroundStyle(Color.text3)
                }
            }
            .onTapGesture {
                viewModel.goToToday()
            }

            Spacer()

            Button {
                viewModel.goToNextDay()
            } label: {
                Image(systemName: "chevron.right")
                    .font(.body.weight(.semibold))
                    .foregroundStyle(
                        viewModel.selectedDate.isToday ? Color.text4 : Color.accentWarm
                    )
                    .frame(width: 44, height: 44)
            }
            .disabled(viewModel.selectedDate.isToday)
        }
        .padding(.horizontal, 4)
        .padding(.vertical, 4)
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 14))
        .shadow(color: .black.opacity(0.03), radius: 4, y: 2)
    }

    // MARK: - Macro Summary

    private var macroSummaryCard: some View {
        VStack(spacing: 16) {
            // Calories ring
            HStack(spacing: 20) {
                MacroRingLarge(
                    current: viewModel.totalCalories,
                    goal: viewModel.goal.calories,
                    color: .caloriesColor,
                    size: 100,
                    lineWidth: 9
                )

                VStack(alignment: .leading, spacing: 10) {
                    macroRow("Protein", current: viewModel.totalProtein, goal: viewModel.goal.protein, color: .proteinColor)
                    macroRow("Carbs", current: viewModel.totalCarbs, goal: viewModel.goal.carbs, color: .carbsColor)
                    macroRow("Fat", current: viewModel.totalFat, goal: viewModel.goal.fat, color: .fatColor)
                }
                .frame(maxWidth: .infinity)
            }
        }
        .padding(20)
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .shadow(color: .black.opacity(0.04), radius: 8, y: 4)
    }

    private func macroRow(_ label: String, current: Double, goal: Double, color: Color) -> some View {
        VStack(spacing: 4) {
            HStack {
                Text(label)
                    .font(.caption.weight(.medium))
                    .foregroundStyle(Color.text3)
                Spacer()
                Text("\(Int(current))/\(Int(goal))g")
                    .font(.caption.weight(.semibold))
                    .foregroundStyle(Color.text2)
            }
            MacroBarCompact(current: current, goal: goal, color: color)
        }
    }

    // MARK: - Add Button

    private var addButton: some View {
        Button {
            showFoodSearch = true
        } label: {
            Image(systemName: "plus")
                .font(.title2.weight(.semibold))
                .foregroundStyle(.white)
                .frame(width: 56, height: 56)
                .background(Color.accentWarm)
                .clipShape(Circle())
                .shadow(color: Color.accentWarm.opacity(0.3), radius: 8, y: 4)
        }
        .padding(20)
    }
}
