// // CompletedWorkoutsView.swift // Werkout_ios // // Created by Trey Tartt on 6/16/24. // import SwiftUI struct CompletedWorkoutsView: View { @State private var completedWorkouts: [CompletedWorkout]? @State private var showCompletedWorkouts: Bool = false @State private var loadError: String? var body: some View { VStack(alignment: .leading) { if let completedWorkouts = completedWorkouts { Divider() .overlay(WerkoutTheme.divider) Text("Workout History:") .font(WerkoutTheme.sectionTitle) .foregroundStyle(WerkoutTheme.textPrimary) HStack { Text("Number of workouts:") .font(WerkoutTheme.bodyText) .foregroundStyle(WerkoutTheme.textSecondary) Text("\(completedWorkouts.count)") .font(WerkoutTheme.bodyText) .foregroundStyle(WerkoutTheme.accent) } if let lastWorkout = completedWorkouts.last { HStack { Text("Last workout:") .font(WerkoutTheme.bodyText) .foregroundStyle(WerkoutTheme.textSecondary) Text(lastWorkout.workoutStartTime) .font(WerkoutTheme.bodyText) .foregroundStyle(WerkoutTheme.accent) } Button("View All Workouts", action: { showCompletedWorkouts = true }) .font(.system(size: 16, weight: .bold)) .foregroundStyle(WerkoutTheme.textPrimary) .frame(maxWidth: .infinity, alignment: .center) .frame(height: 44) .glassEffect(.regular.interactive()) .tint(WerkoutTheme.accent) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.buttonRadius, style: .continuous)) .padding() .frame(maxWidth: .infinity) } } else { if let loadError = loadError { Text(loadError) .font(WerkoutTheme.bodyText) .foregroundStyle(WerkoutTheme.danger) } else { Text("loading completed workouts") .font(WerkoutTheme.bodyText) .foregroundStyle(WerkoutTheme.textMuted) } } } .padding(WerkoutTheme.md) .background(WerkoutTheme.surfaceCard) .clipShape(RoundedRectangle(cornerRadius: WerkoutTheme.cardRadius, style: .continuous)) .onAppear{ fetchCompletedWorkouts() } .refreshable { await withCheckedContinuation { continuation in CompletedWorkoutFetchable().fetch(completion: { result in DispatchQueue.main.async { switch result { case .success(let model): self.completedWorkouts = model self.loadError = nil case .failure(let failure): self.loadError = "Unable to load workout history: \(failure.localizedDescription)" } continuation.resume() } }) } } .sheet(isPresented: $showCompletedWorkouts) { if let completedWorkouts = completedWorkouts { WorkoutHistoryView(completedWorkouts: completedWorkouts) } } } func fetchCompletedWorkouts() { CompletedWorkoutFetchable().fetch(completion: { result in switch result { case .success(let model): DispatchQueue.main.async { completedWorkouts = model loadError = nil } case .failure(let failure): DispatchQueue.main.async { loadError = "Unable to load workout history: \(failure.localizedDescription)" } } }) } } #Preview { CompletedWorkoutsView() }