//
//  MaintenanceListView.swift
//  Gas Man
//
//  Created by Kameron Kenny on 3/17/25.
//


import SwiftUI
import CoreData

struct MaintenanceListView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \MaintenanceEvent.date, ascending: false)],
        animation: .default)
    private var maintenanceEvents: FetchedResults<MaintenanceEvent>
    
    @State private var showingAddMaintenance = false
    
    var body: some View {
        NavigationView {
            List {
                ForEach(maintenanceEvents) { event in
                    VStack(alignment: .leading, spacing: 4) {
                        Text("Date: \(event.date ?? Date(), formatter: dateFormatter)")
                        Text("Odometer: \(event.odometer, specifier: "%.0f") miles")
                        Text("Type: \(event.eventType)")
                        Text("Cost: $\(event.cost, specifier: "%.2f")")
                        if let notes = event.notes, !notes.isEmpty {
                            Text("Notes: \(notes)")
                        }
                        if let locationName = event.locationName, !locationName.isEmpty {
                            Text("Location: \(locationName)")
                        }
                        if let locationCoordinates = event.locationCoordinates, !locationCoordinates.isEmpty {
                            Text("Coordinates: \(locationCoordinates)")
                        }
                    }
                }
                .onDelete(perform: deleteMaintenance)
            }
            .navigationTitle("Maintenance")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: { showingAddMaintenance.toggle() }) {
                        Label("Add Maintenance", systemImage: "plus")
                    }
                }
                ToolbarItem(placement: .navigationBarLeading) {
                    EditButton()
                }
            }
            .sheet(isPresented: $showingAddMaintenance) {
                AddMaintenanceView().environment(\.managedObjectContext, viewContext)
            }
        }
    }
    
    private func deleteMaintenance(offsets: IndexSet) {
        withAnimation {
            offsets.map { maintenanceEvents[$0] }.forEach(viewContext.delete)
            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

private let dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .short
    return formatter
}()
