//
// 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 exerciseLists: [String: ExerciseListLoader.ExerciseListData] = [:]
    @State private var selectedListName: String? = nil
    @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 {
            Group {
                if selectedListName == nil {
                    // Show list of exercise list files
                    List {
                        ForEach(Array(exerciseLists.keys.sorted()), id: \.self) { fileName in
                            if let list = exerciseLists[fileName] {
                                Button(action: {
                                    selectedListName = fileName
                                }) {
                                    VStack(alignment: .leading) {
                                        Text(list.name)
                                            .font(.headline)
                                        Text(list.source)
                                            .font(.subheadline)
                                            .foregroundColor(.secondary)
                                        Text("\(list.exercises.count) exercises")
                                            .font(.caption)
                                            .foregroundColor(.secondary)
                                    }
                                    .padding(.vertical, 4)
                                }
                            }
                        }
                    }
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button("Cancel") {
                                dismiss()
                            }
                        }
                    }
                    .navigationTitle("Exercise Lists")
                } else if let fileName = selectedListName, let list = exerciseLists[fileName] {
                    // Show exercises in the selected list grouped by split
                    List {
                        let exercisesByGroup = Dictionary(grouping: list.exercises) { $0.split }
                        let sortedGroups = exercisesByGroup.keys.sorted()

                        ForEach(sortedGroups, id: \.self) { splitName in
                            Section(header: Text(splitName)) {
                                ForEach(exercisesByGroup[splitName]?.sorted(by: { $0.name < $1.name }) ?? [], id: \.id) { exercise in
                                    if allowMultiSelect {
                                        Button(action: {
                                            if selectedExercises.contains(exercise.name) {
                                                selectedExercises.remove(exercise.name)
                                            } else {
                                                selectedExercises.insert(exercise.name)
                                            }
                                        }) {
                                            HStack {
                                                VStack(alignment: .leading) {
                                                    Text(exercise.name)
                                                        .font(.headline)
                                                    Text(exercise.type)
                                                        .font(.caption)
                                                        .foregroundColor(.secondary)
                                                }
                                                .padding(.vertical, 2)

                                                Spacer()

                                                if selectedExercises.contains(exercise.name) {
                                                    Image(systemName: "checkmark")
                                                        .foregroundColor(.accentColor)
                                                }
                                            }
                                        }
                                    } else {
                                        Button(action: {
                                            onExerciseSelected([exercise.name])
                                            dismiss()
                                        }) {
                                            VStack(alignment: .leading) {
                                                Text(exercise.name)
                                                    .font(.headline)
                                                Text(exercise.type)
                                                    .font(.caption)
                                                    .foregroundColor(.secondary)
                                            }
                                            .padding(.vertical, 2)
                                        }
                                    }
                                }
                            }
                        }
                    }
                    .toolbar {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button("Back") {
                                selectedListName = nil
                                selectedExercises.removeAll()
                            }
                        }
                        if allowMultiSelect {
                            ToolbarItem(placement: .navigationBarTrailing) {
                                Button("Select") {
                                    if !selectedExercises.isEmpty {
                                        onExerciseSelected(Array(selectedExercises))
                                        dismiss()
                                    }
                                }
                                .disabled(selectedExercises.isEmpty)
                            }
                        }
                    }
                    .navigationTitle(list.name)
                }
            }
        }
        .onAppear {
            exerciseLists = ExerciseListLoader.loadExerciseLists()
        }
    }
}
