//
//  PlanWorkoutView.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 7/2/23.
//

import SwiftUI

struct PlanWorkoutView: View {
    @State var selectedDate = Date()
    let workout: Workout
    @Environment(\.dismiss) var dismiss
    var addedPlannedWorkout: (() -> Void)?
    
    var body: some View {
        VStack() {
            Text(workout.name)
                .font(.title)

            Text(selectedDate.formatted(date: .abbreviated, time: .omitted))
                .font(.system(size: 28))
                .bold()
                .foregroundColor(Color.accentColor)
                .padding()
                .animation(.spring(), value: selectedDate)
            
            Divider().frame(height: 1)
         
            DatePicker("Select Date", selection: $selectedDate, displayedComponents: [.date])
                .padding(.horizontal)
                .datePickerStyle(.graphical)
            
            Divider()
            
            HStack {
                Button(action: {
                    planWorkout()
                }, label: {
                    Image(systemName: "plus.app")
                        .font(.title)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                })
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 44)
                .foregroundColor(.blue)
                .background(.yellow)
                .cornerRadius(8)
                .padding()
                
                Button(action: {
                    dismiss()
                }, label: {
                    Image(systemName: "xmark.octagon.fill")
                        .font(.title)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                })
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 44)
                .foregroundColor(.white)
                .background(.red)
                .cornerRadius(8)
                .padding()
            }
            
            Spacer()
        }
        .padding()
    }
    
    func planWorkout() {
        let postData = [
            "on_date": selectedDate.formatForPlannedWorkout,
            "workout": workout.id
        ] as [String : Any]
        
        PlanWorkoutFetchable(postData: postData).fetch(completion: { result in
            switch result {
            case .success(_):
                UserStore.shared.fetchPlannedWorkouts()
                dismiss()
                addedPlannedWorkout?()
            case .failure(_):
                fatalError("shit broke")
            }
        })
    }
}

struct PlanWorkoutView_Previews: PreviewProvider {
    static var previews: some View {
        PlanWorkoutView(workout: PreviewData.workout())
    }
}
