import SwiftUI

struct LabelCreationView: View {

    @Environment(\.colorScheme)
    private var colorScheme

    @Environment(\.language)
    private var language

    @Binding
    var labels: [ContentLabel]

    @State
    private var showWorkoutSelection = false

    @State
    private var selectedWorkouts: [FileResource] = []

    var body: some View {
        List {
            ForEach($labels, id: \.icon) { label in
                HStack {
                    Button(action: { remove(label.wrappedValue) }) {
                        Image(systemSymbol: .minusCircleFill)
                            .foregroundStyle(.red)
                    }
                    .buttonStyle(.plain)
                    LabelEditingView(label: label)
                }
                .padding(.vertical, 2)
                .padding(.horizontal, 8)
                .background(colorScheme == .light ? Color.white : Color.black)
                .cornerRadius(8)
            }
            .onMove(perform: moveLabel)
            Button("Load workout") { showWorkoutSelection = true }
                .padding(.vertical, 2)
            Button("Add new label", action: addLabel)
            .padding(.vertical, 2)
        }
        .frame(minHeight: 250)
        .sheet(isPresented: $showWorkoutSelection) {
            MultiFileSelectionView(
                selectedFiles: $selectedWorkouts,
                allowedType: .route)
        }
        .onChange(of: selectedWorkouts) {
            let workouts = selectedWorkouts.compactMap { $0.routeOverview }
            guard !workouts.isEmpty else {
                return
            }
            let overview = RouteOverview.combine(workouts)
            overview.update(labels: &labels, language: language)
        }
    }

    private func addLabel() {
        for icon in PageIcon.allCases {
            if labels.contains(where: { $0.icon == icon }) {
                continue
            }
            labels.append(.init(icon: icon, value: "Value"))
            return
        }
    }

    private func remove(_ label: ContentLabel) {
        guard let index = labels.firstIndex(of: label) else {
            return
        }
        labels.remove(at: index)
    }

    private func moveLabel(from source: IndexSet, to destination: Int) {
        labels.move(fromOffsets: source, toOffset: destination)
    }
}
