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

import SwiftUI

struct AllMusclesView: View {
    @Binding var selectedMuscles: [Muscle]
    @State var createWorkoutItemPickerViewModel: CreateWorkoutItemPickerViewModel?

    var body: some View {
        VStack {
            if let _ = DataStore.shared.allMuscles {
                Text("Select Muscles")
                    .foregroundColor(.cyan)
                Text("\(selectedMuscles.count) Selected")
            }
        }
        .onTapGesture {
            if let muscles = DataStore.shared.allMuscles {
                var createWorkoutItemPickerModels = [CreateWorkoutItemPickerModel]()
                muscles.forEach({
                    let model = CreateWorkoutItemPickerModel(id: $0.id, name: $0.name.lowercased())
                    createWorkoutItemPickerModels.append(model)
                })
                createWorkoutItemPickerModels = createWorkoutItemPickerModels.sorted(by: {
                    $0.name < $1.name
                })
                let selectedIds = selectedMuscles.map { $0.id }
                createWorkoutItemPickerViewModel = CreateWorkoutItemPickerViewModel(allValues: createWorkoutItemPickerModels, selectedIds: selectedIds)
            }
        }
        .onAppear{
            if #function.hasPrefix("__preview") {
                DataStore.shared.setupFakeData()
            }
            guard let _ = DataStore.shared.allExercise,
                  let muscles = DataStore.shared.allMuscles,
                  let _ = DataStore.shared.allEquipment else {
                return
            }
            selectedMuscles = muscles
        }
        .sheet(item: $createWorkoutItemPickerViewModel) { item in
            CreateWorkoutItemPickerView(viewModel: item, completed: { selectedids in
                if let muscles = DataStore.shared.allMuscles {
                    selectedMuscles.removeAll()
                    for id in selectedids {
                        if let muscle = muscles.first(where: {
                            $0.id == id
                        }) {
                            selectedMuscles.append(muscle)
                        }
                    }
                }
            })
        }
    }
}

//#Preview {
//    AllMusclesView()
//}
