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

import SwiftUI

struct AddVehicleView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.dismiss) var dismiss

    // 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 notes
    @State private var notes: String = ""
    
    // New additional vehicle fields
    @State private var engineName: String = ""
    @State private var engineDisplacement: String = ""
    @State private var transmission: String = "Automatic"  // default value
    @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 = ""
    
    // New additional vehicle fields for tire and wheel info:
    @State private var tireBrand: String = ""
    @State private var tireModel: String = ""
    @State private var wheelBrand: String = ""
    @State private var wheelModel: String = ""
    
    private let dateFormatter: DateFormatter = {
         let formatter = DateFormatter()
         formatter.dateStyle = .short
         return formatter
    }()
    
    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("Add Vehicle")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save") { saveVehicle() }
                }
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") { dismiss() }
                }
            }
        }
    }
    
    private func saveVehicle() {
        let newVehicle = Vehicle(context: viewContext)
        newVehicle.id = UUID()
        newVehicle.year = year
        newVehicle.make = make
        newVehicle.model = model
        newVehicle.color = color
        newVehicle.purchaseDate = purchaseDateEnabled ? purchaseDate : nil
        newVehicle.purchasePrice = Double(purchasePrice).map { NSNumber(value: $0) }
        newVehicle.odometerAtPurchase = Double(odometerAtPurchase).map { NSNumber(value: $0) }
        newVehicle.soldDate = soldDateEnabled ? soldDate : nil
        newVehicle.odometerAtSale = Double(odometerAtSale).map { NSNumber(value: $0) }
        newVehicle.notes = notes.isEmpty ? nil : notes
        newVehicle.tireBrand = tireBrand.isEmpty ? nil : tireBrand
        newVehicle.tireModel = tireModel.isEmpty ? nil : tireModel
        newVehicle.wheelBrand = wheelBrand.isEmpty ? nil : wheelBrand
        newVehicle.wheelModel = wheelModel.isEmpty ? nil : wheelModel
        
        // Save additional vehicle information:
        newVehicle.engineName = engineName.isEmpty ? nil : engineName
        newVehicle.engineDisplacement = Double(engineDisplacement).map { NSNumber(value: $0) }
        newVehicle.transmission = transmission.isEmpty ? "Automatic" : transmission
        newVehicle.vehicleType = vehicleType.isEmpty ? nil : vehicleType
        newVehicle.wheelSizeWidth = Double(wheelSizeWidth).map { NSNumber(value: $0) }
        newVehicle.wheelSizeDiameter = Double(wheelSizeDiameter).map { NSNumber(value: $0) }
        newVehicle.tireSizeWidth = Double(tireSizeWidth).map { NSNumber(value: $0) }
        newVehicle.tireSizeHeight = Double(tireSizeHeight).map { NSNumber(value: $0) }
        newVehicle.tireSizeRadius = Double(tireSizeRadius).map { NSNumber(value: $0) }
        
        do {
            try viewContext.save()
            dismiss()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

