//
//  CompletedWorkoutsView.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/16/24.
//

import SwiftUI

struct CompletedWorkoutsView: View {
    @State var completedWorkouts: [CompletedWorkout]?
    @State var showCompletedWorkouts: Bool = false

    var body: some View {
        VStack(alignment: .leading) {
            if let completedWorkouts = completedWorkouts {
                
                Divider()
                Text("Workout History:")
                HStack {
                    Text("Number of workouts:")
                    Text("\(completedWorkouts.count)")
                }
                
                if let lastWorkout = completedWorkouts.last {
                    HStack {
                        Text("Last workout:")
                        Text(lastWorkout.workoutStartTime)
                    }
                    
                    Button("View All Workouts", action: {
                        showCompletedWorkouts = true
                    })
                    .frame(maxWidth: .infinity, alignment: .center)
                    .frame(height: 44)
                    .foregroundColor(.blue)
                    .background(.yellow)
                    .cornerRadius(8)
                    .padding()
                    .frame(maxWidth: .infinity)
                }
                
            } else {
                Text("loading completed workouts")
            }
        }
        .onAppear{
            fetchCompletedWorkouts()
        }
        .sheet(isPresented: $showCompletedWorkouts) {
            if let completedWorkouts = completedWorkouts {
                WorkoutHistoryView(completedWorkouts: completedWorkouts)
            }
        }
    }
    
    func fetchCompletedWorkouts() {
        CompletedWorkoutFetchable().fetch(completion: { result in
            switch result {
            case .success(let model):
                completedWorkouts = model
            case .failure(let failure):
                fatalError(failure.localizedDescription)
            }
        })
    }
}

#Preview {
    CompletedWorkoutsView()
}
