import SwiftUI

struct GoalsView: View {
    @State private var vm = GoalsViewModel()

    var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                if vm.isLoading {
                    LoadingView()
                } else if vm.goal != nil {
                    goalEditor
                } else {
                    EmptyStateView(
                        icon: "target",
                        title: "No active goal",
                        subtitle: vm.error ?? "Set goals from the web app"
                    )
                }

                Spacer(minLength: 80)
            }
            .padding(.horizontal)
            .padding(.top, 8)
        }
        .background(Color.canvas)
        .scrollDismissesKeyboard(.interactively)
        .onTapGesture {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
        }
        .task {
            await vm.load()
        }
        .refreshable {
            await vm.load()
        }
    }

    private var goalEditor: some View {
        VStack(spacing: 16) {
            Text("Daily Goals")
                .font(.headline)
                .foregroundStyle(Color.textPrimary)
                .frame(maxWidth: .infinity, alignment: .leading)

            LazyVGrid(columns: [
                GridItem(.flexible()),
                GridItem(.flexible()),
            ], spacing: 16) {
                goalField("Calories", text: $vm.editCalories, unit: "kcal", color: .emerald)
                goalField("Protein", text: $vm.editProtein, unit: "g", color: .macroProtein)
                goalField("Carbs", text: $vm.editCarbs, unit: "g", color: .macroCarbs)
                goalField("Fat", text: $vm.editFat, unit: "g", color: .macroFat)
                goalField("Sugar", text: $vm.editSugar, unit: "g", color: .orange)
                goalField("Fiber", text: $vm.editFiber, unit: "g", color: .green)
            }

            if let goal = vm.goal {
                HStack {
                    Text("Active since \(goal.startDate)")
                        .font(.caption)
                        .foregroundStyle(Color.textTertiary)
                    Spacer()
                }
            }

            if vm.saveSuccess {
                HStack {
                    Image(systemName: "checkmark.circle.fill")
                        .foregroundStyle(Color.emerald)
                    Text("Goals saved")
                        .font(.caption.weight(.medium))
                        .foregroundStyle(Color.emerald)
                    Spacer()
                }
            }

            if let error = vm.error {
                Text(error)
                    .font(.caption)
                    .foregroundStyle(.red)
            }

            Button {
                Task { await vm.save() }
            } label: {
                HStack {
                    if vm.isSaving {
                        ProgressView()
                            .controlSize(.small)
                            .tint(.white)
                    }
                    Text("Save Goals")
                        .font(.subheadline.weight(.semibold))
                }
                .foregroundStyle(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 12)
                .background(Color.emerald)
                .clipShape(RoundedRectangle(cornerRadius: 10))
            }
            .disabled(vm.isSaving)
        }
        .padding()
        .background(Color.surfaceCard)
        .clipShape(RoundedRectangle(cornerRadius: 14))
        .shadow(color: .black.opacity(0.04), radius: 6, y: 2)
    }

    private func goalField(_ label: String, text: Binding<String>, unit: String, color: Color) -> some View {
        VStack(spacing: 6) {
            TextField("0", text: text)
                .font(.title2.weight(.bold).monospacedDigit())
                .foregroundStyle(color)
                .multilineTextAlignment(.center)
                .keyboardType(.numberPad)
            Text(unit)
                .font(.caption2)
                .foregroundStyle(Color.textTertiary)
            Text(label)
                .font(.caption.weight(.medium))
                .foregroundStyle(Color.textSecondary)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 12)
        .background(color.opacity(0.06))
        .clipShape(RoundedRectangle(cornerRadius: 10))
    }
}
