import SwiftUI

struct TemplatesView: View {
    @State private var vm = TemplatesViewModel()
    @State private var confirmTemplate: MealTemplate?
    @State private var logMealType: MealType = .snack
    @State private var showConfirmation = false
    @State private var logResult: String?

    var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                if vm.isLoading {
                    LoadingView()
                } else if vm.templates.isEmpty {
                    EmptyStateView(
                        icon: "doc.text",
                        title: "No templates",
                        subtitle: "Create meal templates from the web app"
                    )
                } else {
                    ForEach(vm.groupedByMealType, id: \.0) { group, templates in
                        VStack(alignment: .leading, spacing: 8) {
                            Text(group)
                                .font(.caption.weight(.semibold))
                                .foregroundStyle(Color.textTertiary)
                                .textCase(.uppercase)
                                .padding(.horizontal, 4)

                            ForEach(templates) { template in
                                templateCard(template)
                            }
                        }
                    }
                }

                Spacer(minLength: 80)
            }
            .padding(.horizontal)
            .padding(.top, 8)
        }
        .background(Color.canvas)
        .task {
            await vm.load()
        }
        .refreshable {
            await vm.load()
        }
        .alert("Log Template", isPresented: $showConfirmation) {
            Button("Log") {
                guard let template = confirmTemplate else { return }
                Task {
                    do {
                        let result = try await vm.logTemplate(
                            template,
                            mealType: logMealType.rawValue,
                            entryDate: Date().apiDateString
                        )
                        logResult = "Logged \(result.logged) items"
                    } catch {
                        logResult = error.localizedDescription
                    }
                }
            }
            Button("Cancel", role: .cancel) {}
        } message: {
            if let template = confirmTemplate {
                Text("Add \(template.items.count) items from \"\(template.name)\" to \(logMealType.displayName)?")
            }
        }
        .alert("Result", isPresented: .init(
            get: { logResult != nil },
            set: { if !$0 { logResult = nil } }
        )) {
            Button("OK") { logResult = nil }
        } message: {
            Text(logResult ?? "")
        }
    }

    private func templateCard(_ template: MealTemplate) -> some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Text(template.name)
                    .font(.headline)
                    .foregroundStyle(Color.textPrimary)
                Spacer()

                let totalCals = template.items.reduce(0.0) { $0 + $1.calories }
                Text("\(Int(totalCals)) kcal")
                    .font(.subheadline.weight(.medium))
                    .foregroundStyle(Color.textSecondary)
            }

            ForEach(template.items) { item in
                HStack {
                    Text(item.foodName)
                        .font(.caption)
                        .foregroundStyle(Color.textSecondary)
                    Spacer()
                    Text("\(Int(item.calories)) kcal")
                        .font(.caption)
                        .foregroundStyle(Color.textTertiary)
                }
            }

            HStack {
                Spacer()
                Button {
                    confirmTemplate = template
                    logMealType = MealType(rawValue: template.mealType ?? "snack") ?? .snack
                    showConfirmation = true
                } label: {
                    Label("Log", systemImage: "plus.circle.fill")
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(Color.accentWarm)
                }
            }
        }
        .padding()
        .background(Color.surfaceCard)
        .clipShape(RoundedRectangle(cornerRadius: 12))
        .shadow(color: .black.opacity(0.04), radius: 4, y: 2)
    }
}
