//
//  VehicleListView.swift
//  Gas Man
//
//  Created by Kameron Kenny on 3/18/25.
//


import SwiftUI
import CoreData

struct VehicleListView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Vehicle.make, ascending: true)],
        animation: .default)
    private var vehicles: FetchedResults<Vehicle>
    
    @State private var showingAddVehicle = false
    
    var body: some View {
        NavigationView {
            List {
                ForEach(vehicles) { vehicle in
                    NavigationLink(destination: VehicleDetailView(vehicle: vehicle)) {
                        VehicleRowView(vehicle: vehicle)
                    }
                }
                .onDelete(perform: deleteVehicles)
            }
            .navigationTitle("Vehicles")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: { showingAddVehicle = true }) {
                        Label("Add Vehicle", systemImage: "plus")
                    }
                }
                ToolbarItem(placement: .navigationBarLeading) {
                    EditButton()
                }
            }
            .sheet(isPresented: $showingAddVehicle) {
                AddVehicleView().environment(\.managedObjectContext, viewContext)
            }
        }
    }
    
    private func deleteVehicles(offsets: IndexSet) {
        withAnimation {
            offsets.map { vehicles[$0] }.forEach(viewContext.delete)
            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}
