import SwiftUI

struct TemplatesView: View {
    let dateString: String
    let onTemplateLogged: () -> Void

    @State private var viewModel = TemplatesViewModel()
    @State private var confirmTemplate: MealTemplate?

    var body: some View {
        ScrollView {
            if viewModel.isLoading {
                LoadingView(message: "Loading templates...")
                    .frame(height: 300)
            } else if viewModel.templates.isEmpty {
                EmptyStateView(
                    icon: "doc.text",
                    title: "No templates",
                    subtitle: "Create templates on the web app to quickly log meals"
                )
            } else {
                LazyVStack(spacing: 16) {
                    ForEach(MealType.allCases) { meal in
                        let templates = viewModel.groupedTemplates[meal.rawValue] ?? []
                        if !templates.isEmpty {
                            templateSection(meal: meal, templates: templates)
                        }
                    }

                    // Ungrouped
                    let ungrouped = viewModel.templates.filter { template in
                        !MealType.allCases.map(\.rawValue).contains(template.mealType)
                    }
                    if !ungrouped.isEmpty {
                        templateSection(mealLabel: "Other", icon: "ellipsis.circle.fill", color: .text3, templates: ungrouped)
                    }
                }
                .padding(16)
            }

            if let error = viewModel.errorMessage {
                ErrorBanner(message: error) {
                    Task { await viewModel.load() }
                }
                .padding(16)
            }
        }
        .refreshable {
            await viewModel.load()
        }
        .task {
            await viewModel.load()
        }
        .confirmationDialog(
            "Log Template",
            isPresented: Binding(
                get: { confirmTemplate != nil },
                set: { if !$0 { confirmTemplate = nil } }
            ),
            presenting: confirmTemplate
        ) { template in
            Button("Log \"\(template.name)\"") {
                Task {
                    await viewModel.logTemplate(template, date: dateString) {
                        onTemplateLogged()
                    }
                }
            }
            Button("Cancel", role: .cancel) {}
        } message: { template in
            Text("This will add all items from \"\(template.name)\" (\(Int(template.calories)) kcal) to \(dateString).")
        }
    }

    private func templateSection(meal: MealType, templates: [MealTemplate]) -> some View {
        templateSection(
            mealLabel: meal.displayName,
            icon: meal.icon,
            color: Color.mealColor(for: meal.rawValue),
            templates: templates
        )
    }

    private func templateSection(mealLabel: String, icon: String, color: Color, templates: [MealTemplate]) -> some View {
        VStack(alignment: .leading, spacing: 10) {
            HStack(spacing: 8) {
                Image(systemName: icon)
                    .foregroundStyle(color)
                Text(mealLabel)
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(Color.text1)
            }

            ForEach(templates) { template in
                TemplateCard(
                    template: template,
                    isLogging: viewModel.loggedTemplateId == template.id
                ) {
                    confirmTemplate = template
                }
            }
        }
    }
}

struct TemplateCard: View {
    let template: MealTemplate
    let isLogging: Bool
    let onLog: () -> Void

    var body: some View {
        HStack(spacing: 14) {
            // Icon
            ZStack {
                RoundedRectangle(cornerRadius: 10)
                    .fill(Color.mealColor(for: template.mealType).opacity(0.1))
                    .frame(width: 44, height: 44)

                Image(systemName: "doc.text.fill")
                    .foregroundStyle(Color.mealColor(for: template.mealType))
            }

            // Info
            VStack(alignment: .leading, spacing: 4) {
                Text(template.name)
                    .font(.subheadline.weight(.medium))
                    .foregroundStyle(Color.text1)
                    .lineLimit(1)

                HStack(spacing: 8) {
                    Text("\(Int(template.calories)) kcal")
                        .font(.caption.weight(.semibold))
                        .foregroundStyle(Color.caloriesColor)

                    if let count = template.itemsCount {
                        Text("\(count) items")
                            .font(.caption)
                            .foregroundStyle(Color.text4)
                    }

                    if let protein = template.protein {
                        Text("P\(Int(protein))")
                            .font(.caption)
                            .foregroundStyle(Color.proteinColor)
                    }
                }
            }

            Spacer()

            // Log button
            Button(action: onLog) {
                if isLogging {
                    ProgressView()
                        .controlSize(.small)
                        .tint(Color.accentWarm)
                } else {
                    Image(systemName: "plus.circle.fill")
                        .font(.title3)
                        .foregroundStyle(Color.accentWarm)
                }
            }
            .disabled(isLogging)
        }
        .padding(14)
        .background(Color.surface)
        .clipShape(RoundedRectangle(cornerRadius: 14))
        .shadow(color: .black.opacity(0.03), radius: 4, y: 2)
    }
}
