//
// ExercisePickerView.swift
// Workouts
//
// Created by rzen on 7/13/25 at 7:17 PM.
//
// Copyright 2025 Rouslan Zenetl. All Rights Reserved.
//

import SwiftUI

struct ExercisePickerView: View {
    @Environment(\.dismiss) private var dismiss
    @State private var selectedExercises: Set<String> = []

    var onExerciseSelected: ([String]) -> Void
    var allowMultiSelect: Bool = false

    init(onExerciseSelected: @escaping ([String]) -> Void, allowMultiSelect: Bool = false) {
        self.onExerciseSelected = onExerciseSelected
        self.allowMultiSelect = allowMultiSelect
    }

    var body: some View {
        NavigationStack {
            List(ExerciseMotionLibrary.exerciseNames, id: \.self) { exerciseName in
                if allowMultiSelect {
                    Button(action: {
                        if selectedExercises.contains(exerciseName) {
                            selectedExercises.remove(exerciseName)
                        } else {
                            selectedExercises.insert(exerciseName)
                        }
                    }) {
                        HStack {
                            Text(exerciseName)
                            Spacer()
                            if selectedExercises.contains(exerciseName) {
                                Image(systemName: "checkmark")
                                    .foregroundColor(.accentColor)
                            }
                        }
                    }
                } else {
                    Button(action: {
                        onExerciseSelected([exerciseName])
                        dismiss()
                    }) {
                        Text(exerciseName)
                    }
                }
            }
            .navigationTitle("Exercise Library")
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") {
                        dismiss()
                    }
                }
                if allowMultiSelect {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button("Select") {
                            if !selectedExercises.isEmpty {
                                onExerciseSelected(Array(selectedExercises))
                                dismiss()
                            }
                        }
                        .disabled(selectedExercises.isEmpty)
                    }
                }
            }
        }
    }
}
