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


import SwiftUI

struct EditVehicleView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.dismiss) var dismiss
    
    @ObservedObject var vehicle: Vehicle
    
    // Basic Information
    @State private var year: String = ""
    @State private var make: String = ""
    @State private var model: String = ""
    @State private var color: String = ""
    
    // Purchase Information
    @State private var purchaseDate: Date = Date()
    @State private var purchaseDateEnabled: Bool = false
    @State private var purchasePrice: String = ""
    @State private var odometerAtPurchase: String = ""
    
    // Sale Information
    @State private var soldDate: Date = Date()
    @State private var soldDateEnabled: Bool = false
    @State private var odometerAtSale: String = ""
    
    // Additional Vehicle Information
    @State private var engineName: String = ""
    @State private var engineDisplacement: String = ""
    @State private var transmission: String = "Automatic" // default
    @State private var vehicleType: String = ""
    @State private var wheelSizeWidth: String = ""
    @State private var wheelSizeDiameter: String = ""
    @State private var tireSizeWidth: String = ""
    @State private var tireSizeHeight: String = ""
    @State private var tireSizeRadius: String = ""
    
    // Tire & Wheel Brand/Model
    @State private var tireBrand: String = ""
    @State private var tireModel: String = ""
    @State private var wheelBrand: String = ""
    @State private var wheelModel: String = ""
    
    // Additional Notes
    @State private var notes: String = ""
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Basic Information")) {
                    Picker("Vehicle Type", selection: $vehicleType) {
                        Text("Sedan").tag("Sedan")
                        Text("SUV").tag("SUV")
                        Text("Truck").tag("Truck")
                        Text("Van").tag("Van")
                    }
                    .pickerStyle(MenuPickerStyle())
                    TextField("Year", text: $year)
                        .keyboardType(.numberPad)
                    TextField("Make", text: $make)
                    TextField("Model", text: $model)
                    TextField("Color", text: $color)
                }
                Section(header: Text("Purchase Information")) {
                    Toggle("Add Purchase Date", isOn: $purchaseDateEnabled)
                    if purchaseDateEnabled {
                        DatePicker("Purchase Date", selection: $purchaseDate, displayedComponents: .date)
                        TextField("Purchase Price", text: $purchasePrice)
                            .keyboardType(.decimalPad)
                        TextField("Odometer at Purchase", text: $odometerAtPurchase)
                            .keyboardType(.decimalPad)
                    }
                }
                Section(header: Text("Engine & Transmission")) {
                    TextField("Engine Name", text: $engineName)
                    TextField("Engine Displacement (L)", text: $engineDisplacement)
                        .keyboardType(.decimalPad)
                    Picker("Transmission", selection: $transmission) {
                        Text("Automatic").tag("Automatic")
                        Text("Manual").tag("Manual")
                    }
                    .pickerStyle(MenuPickerStyle())
                }
                
                Section(header: Text("Tires")) {
                    TextField("Tire Brand", text: $tireBrand)
                    TextField("Tire Model", text: $tireModel)
                    TextField("Tire Size Width", text: $tireSizeWidth)
                        .keyboardType(.decimalPad)
                    TextField("Tire Size Height", text: $tireSizeHeight)
                        .keyboardType(.decimalPad)
                    TextField("Tire Size Radius", text: $tireSizeRadius)
                        .keyboardType(.decimalPad)
                }
                
                Section(header: Text("Wheels")) {
                    TextField("Wheel Brand", text: $wheelBrand)
                    TextField("Wheel Model", text: $wheelModel)
                    TextField("Wheel Size Width", text: $wheelSizeWidth)
                        .keyboardType(.decimalPad)
                    TextField("Wheel Size Diameter", text: $wheelSizeDiameter)
                        .keyboardType(.decimalPad)
                }
                Section(header: Text("Sale Information")) {
                    Toggle("Add Sold Date", isOn: $soldDateEnabled)
                    if soldDateEnabled {
                        DatePicker("Date Sold", selection: $soldDate, displayedComponents: .date)
                        TextField("Odometer at Sale", text: $odometerAtSale)
                            .keyboardType(.decimalPad)
                    }

                }
                Section(header: Text("Notes")) {
                    TextField("Notes", text: $notes)
                }
            }
            .navigationTitle("Edit Vehicle")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save") { saveChanges() }
                }
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") { dismiss() }
                }
            }
        }
        .onAppear(perform: loadVehicleData)
    }
    
    private func loadVehicleData() {
        // Basic Information
        year = vehicle.year ?? ""
        make = vehicle.make ?? ""
        model = vehicle.model ?? ""
        color = vehicle.color ?? ""
        
        // Purchase Information
        if let pDate = vehicle.purchaseDate {
            purchaseDate = pDate
            purchaseDateEnabled = true
        } else {
            purchaseDateEnabled = false
        }
        if let pPrice = vehicle.purchasePrice?.doubleValue {
            purchasePrice = String(format: "%.2f", pPrice)
        } else {
            purchasePrice = ""
        }
        if let odoPurchase = vehicle.odometerAtPurchase?.doubleValue {
            odometerAtPurchase = String(format: "%.0f", odoPurchase)
        } else {
            odometerAtPurchase = ""
        }
        
        // Sale Information
        if let sDate = vehicle.soldDate {
            soldDate = sDate
            soldDateEnabled = true
        } else {
            soldDateEnabled = false
        }
        if let odoSale = vehicle.odometerAtSale?.doubleValue {
            odometerAtSale = String(format: "%.0f", odoSale)
        } else {
            odometerAtSale = ""
        }
        
        // Additional Vehicle Information
        engineName = vehicle.engineName ?? ""
        if let ed = vehicle.engineDisplacement?.doubleValue {
            engineDisplacement = String(format: "%.3f", ed)
        } else {
            engineDisplacement = ""
        }
        transmission = vehicle.transmission ?? "Automatic"
        vehicleType = vehicle.vehicleType ?? ""
        if let wsWidth = vehicle.wheelSizeWidth?.doubleValue {
            wheelSizeWidth = String(format: "%.3f", wsWidth)
        } else {
            wheelSizeWidth = ""
        }
        if let wsDiameter = vehicle.wheelSizeDiameter?.doubleValue {
            wheelSizeDiameter = String(format: "%.3f", wsDiameter)
        } else {
            wheelSizeDiameter = ""
        }
        if let tsWidth = vehicle.tireSizeWidth?.doubleValue {
            tireSizeWidth = String(format: "%.3f", tsWidth)
        } else {
            tireSizeWidth = ""
        }
        if let tsHeight = vehicle.tireSizeHeight?.doubleValue {
            tireSizeHeight = String(format: "%.3f", tsHeight)
        } else {
            tireSizeHeight = ""
        }
        if let tsRadius = vehicle.tireSizeRadius?.doubleValue {
            tireSizeRadius = String(format: "%.3f", tsRadius)
        } else {
            tireSizeRadius = ""
        }
        
        // Tire & Wheel Brand/Model
        tireBrand = vehicle.tireBrand ?? ""
        tireModel = vehicle.tireModel ?? ""
        wheelBrand = vehicle.wheelBrand ?? ""
        wheelModel = vehicle.wheelModel ?? ""
        
        // Notes
        notes = vehicle.notes ?? ""
    }
    
    private func saveChanges() {
        vehicle.year = year
        vehicle.make = make
        vehicle.model = model
        vehicle.color = color
        vehicle.purchaseDate = purchaseDateEnabled ? purchaseDate : nil
        vehicle.purchasePrice = Double(purchasePrice).map { NSNumber(value: $0) }
        vehicle.odometerAtPurchase = Double(odometerAtPurchase).map { NSNumber(value: $0) }
        vehicle.soldDate = soldDateEnabled ? soldDate : nil
        vehicle.odometerAtSale = Double(odometerAtSale).map { NSNumber(value: $0) }
        
        vehicle.engineName = engineName.isEmpty ? nil : engineName
        vehicle.engineDisplacement = Double(engineDisplacement).map { NSNumber(value: $0) }
        vehicle.transmission = transmission.isEmpty ? "Automatic" : transmission
        vehicle.vehicleType = vehicleType.isEmpty ? nil : vehicleType
        vehicle.wheelSizeWidth = Double(wheelSizeWidth).map { NSNumber(value: $0) }
        vehicle.wheelSizeDiameter = Double(wheelSizeDiameter).map { NSNumber(value: $0) }
        vehicle.tireSizeWidth = Double(tireSizeWidth).map { NSNumber(value: $0) }
        vehicle.tireSizeHeight = Double(tireSizeHeight).map { NSNumber(value: $0) }
        vehicle.tireSizeRadius = Double(tireSizeRadius).map { NSNumber(value: $0) }
        
        vehicle.tireBrand = tireBrand.isEmpty ? nil : tireBrand
        vehicle.tireModel = tireModel.isEmpty ? nil : tireModel
        vehicle.wheelBrand = wheelBrand.isEmpty ? nil : wheelBrand
        vehicle.wheelModel = wheelModel.isEmpty ? nil : wheelModel
        
        vehicle.notes = notes.isEmpty ? nil : notes
        
        do {
            try viewContext.save()
            dismiss()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}
