import SwiftUI

struct HistoryView: View {
    @State private var viewModel = HistoryViewModel()

    var body: some View {
        ScrollView {
            if viewModel.isLoading {
                LoadingView(message: "Loading history...")
                    .frame(height: 300)
            } else if viewModel.days.isEmpty {
                EmptyStateView(
                    icon: "calendar",
                    title: "No history",
                    subtitle: "Start logging food to see your history"
                )
            } else {
                LazyVStack(spacing: 12) {
                    ForEach(viewModel.days) { day in
                        HistoryDayCard(day: day)
                    }
                }
                .padding(16)
            }

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

struct HistoryDayCard: View {
    let day: HistoryViewModel.HistoryDay
    @State private var isExpanded = false

    var body: some View {
        VStack(spacing: 0) {
            // Header
            Button {
                withAnimation(.easeInOut(duration: 0.2)) {
                    isExpanded.toggle()
                }
            } label: {
                HStack(spacing: 12) {
                    // Date
                    VStack(alignment: .leading, spacing: 2) {
                        Text(day.date.relativeLabel)
                            .font(.subheadline.weight(.semibold))
                            .foregroundStyle(Color.text1)
                        Text(day.date.shortDisplayString)
                            .font(.caption)
                            .foregroundStyle(Color.text3)
                    }

                    Spacer()

                    // Quick stats
                    HStack(spacing: 16) {
                        VStack(spacing: 2) {
                            Text("\(Int(day.totalCalories))")
                                .font(.subheadline.weight(.bold))
                                .foregroundStyle(Color.text1)
                            Text("kcal")
                                .font(.caption2)
                                .foregroundStyle(Color.text4)
                        }

                        // Mini progress ring
                        ZStack {
                            Circle()
                                .stroke(Color.caloriesColor.opacity(0.12), lineWidth: 3)
                            Circle()
                                .trim(from: 0, to: day.calorieProgress)
                                .stroke(Color.caloriesColor, style: StrokeStyle(lineWidth: 3, lineCap: .round))
                                .rotationEffect(.degrees(-90))
                        }
                        .frame(width: 28, height: 28)
                    }

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

            if isExpanded {
                Divider()
                    .padding(.horizontal, 16)

                // Macros row
                HStack(spacing: 0) {
                    historyMacro("Protein", value: day.totalProtein, color: .proteinColor)
                    Spacer()
                    historyMacro("Carbs", value: day.totalCarbs, color: .carbsColor)
                    Spacer()
                    historyMacro("Fat", value: day.totalFat, color: .fatColor)
                    Spacer()
                    historyMacro("Entries", value: Double(day.entryCount), color: .text3, isCount: true)
                }
                .padding(.horizontal, 20)
                .padding(.vertical, 12)

                if !day.entries.isEmpty {
                    Divider()
                        .padding(.horizontal, 16)

                    // Entries list
                    ForEach(day.entries) { entry in
                        HStack(spacing: 8) {
                            Circle()
                                .fill(Color.mealColor(for: entry.mealType))
                                .frame(width: 6, height: 6)

                            Text(entry.foodName)
                                .font(.caption)
                                .foregroundStyle(Color.text2)
                                .lineLimit(1)

                            Spacer()

                            Text("\(Int(entry.calories)) kcal")
                                .font(.caption)
                                .foregroundStyle(Color.text3)
                        }
                        .padding(.horizontal, 20)
                        .padding(.vertical, 4)
                    }
                    .padding(.vertical, 4)
                }
            }
        }
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 14))
        .shadow(color: .black.opacity(0.03), radius: 4, y: 2)
    }

    private func historyMacro(_ label: String, value: Double, color: Color, isCount: Bool = false) -> some View {
        VStack(spacing: 2) {
            Text("\(Int(value))\(isCount ? "" : "g")")
                .font(.subheadline.weight(.semibold))
                .foregroundStyle(color)
            Text(label)
                .font(.caption2)
                .foregroundStyle(Color.text4)
        }
    }
}
