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

import SwiftUI

struct AllEquipmentView: View {
    @Binding var selectedEquipment: [Equipment]
    @State var createWorkoutItemPickerViewModel: CreateWorkoutItemPickerViewModel?

    var body: some View {
        VStack {
            if let _ = DataStore.shared.allEquipment {
                Text("Select Equipment")
                    .foregroundColor(.cyan)
                Text("\(selectedEquipment.count) Selected")
            }
        }
        .onTapGesture {
            if let equipment = DataStore.shared.allEquipment {
                var createWorkoutItemPickerModels = [CreateWorkoutItemPickerModel]()
                equipment.forEach({
                    let model = CreateWorkoutItemPickerModel(id: $0.id,
                                                             name: $0.name.lowercased())
                    createWorkoutItemPickerModels.append(model)
                })
                createWorkoutItemPickerModels = createWorkoutItemPickerModels.sorted(by: {
                    $0.name < $1.name
                })
                let selectedIds = selectedEquipment.map { $0.id }
                createWorkoutItemPickerViewModel = CreateWorkoutItemPickerViewModel(allValues: createWorkoutItemPickerModels, selectedIds: selectedIds)
            }
        }
        .sheet(item: $createWorkoutItemPickerViewModel) { item in
            CreateWorkoutItemPickerView(viewModel: item, completed: { selectedids in
                if let equipment = DataStore.shared.allEquipment {
                    selectedEquipment.removeAll()
                    for id in selectedids {
                        if let equipment = equipment.first(where: {
                            $0.id == id
                        }) {
                            selectedEquipment.append(equipment)
                        }
                    }
                }
            })
        }
    }
}

//#Preview {
//    AllEquipmentview()
//}
