//
//  DistanceBetweenFillupsTrendChartView.swift
//  Gas Man
//
//  Created by Kameron Kenny on 3/19/25.
//


import SwiftUI
import Charts
import CoreData

struct DistanceBetweenFillupsTrendChartView: View {
    let fuelLogs: [FuelLog]
    
    // Compute trend data by sorting logs by date ascending,
    // then mapping each log's date and pricePerGalon.
    var trendData: [(date: Date, distance: Double)] {
        let sortedLogs = fuelLogs.sorted { ($0.date ?? Date()) < ($1.date ?? Date()) }
        var data: [(Date, Double)] = []
        // Start from index 1 because we need a previous log to compute the difference.
        for i in 1..<sortedLogs.count {
            let previous = sortedLogs[i - 1]
            let current = sortedLogs[i]
            if let date = current.date,
               current.odometer > previous.odometer,
               current.fuelVolume > 0 {
                let distance = (current.odometer - previous.odometer)
                data.append((date, distance))
            }
        }
        return data
    }
    
    var body: some View {
        VStack {
            if trendData.isEmpty {
                Text("No trend data available.")
                    .foregroundColor(.secondary)
            } else {
                Chart {
                    ForEach(trendData, id: \.date) { point in
                        LineMark(
                            x: .value("Date", point.date),
                            y: .value("Distance", point.distance)
                        )
                        PointMark(
                            x: .value("Date", point.date),
                            y: .value("Price", point.distance)
                        )
                        .annotation(position: .top) {
                            // This annotation displays the data point number and the MPG value.
                            Text("\(point.distance, specifier: "%.0f")")
                                .font(.caption2)
                                .foregroundColor(.blue)
                        }
                    }
                }
                .chartXAxis {
                    AxisMarks(values: .automatic(desiredCount: 4))
                }
                .chartYAxis {
                    AxisMarks(values: .automatic(desiredCount: 5))
                }
            }
        }
        .padding()
        .navigationTitle("Distance Between Fuel-ups Trend")
    }
}
