import SwiftUI
import Charts

struct SerialChartView: View {
    @State private var timeframe: Timeframe = .twoWeeks
    @State private var topModels: [Model] = []
    
    
    var body: some View {
        VStack {
            Picker("Timeframe", selection: $timeframe) {
                Text("2 Weeks").tag(Timeframe.twoWeeks)
                Text("Month").tag(Timeframe.month)
                Text("Year").tag(Timeframe.year)
            }
           .pickerStyle(.segmented)
           .padding(.bottom, 10)
            
            Text("Top Models")
               .font(.subheadline)
               .foregroundColor(.secondary)
            
            Chart {
                ForEach(topModels.indices, id: \.self) { index in
                    LineMark(
                        x:.value("Day", topModels[index].date),
                        y:.value("Count", topModels[index].serialCount)
                    )
                   .foregroundStyle(by:.value("Model", topModels[index].name))
                   .interpolationMethod(.cardinal)
                   .symbol(by:.value("Model", topModels[index].name))
                }
            }
           .chartLegend(position:.top)
           .chartYScale(domain:.automatic(includesZero: false))
           .chartXAxis {
               AxisMarks(values: .automatic(roundLowerBound: false, roundUpperBound: false)) { value in
                   if value.index < value.count - 1 {
                       AxisValueLabel(format: DateFormatterStyle())
                   }
                   AxisTick()
                   AxisGridLine()
               }
           }
           .frame(minHeight: 300)
        }
       .padding()
       .onAppear {
            updateTopModels()
        }
       .onChange(of: timeframe) { newValue in
            updateTopModels()
        }
    }
    
    private func updateTopModels() {
        // Get the serial history from your app's data storage
        let serialHistory = SerialHistory()
        
        // Filter the serial history based on the selected timeframe
        let filteredSerials: [SerialRecord]
        switch timeframe {
        case.twoWeeks:
            filteredSerials = serialHistory.records.filter { $0.date > Date().addingTimeInterval(-1209600) }
        case.month:
            filteredSerials = serialHistory.records.filter { $0.date > Date().addingTimeInterval(-2592000) }
        case.year:
            filteredSerials = serialHistory.records.filter { $0.date > Date().addingTimeInterval(-31536000) }
        }
        
        // Group the filtered serials by model and count the serials for each model
        let modelCounts = filteredSerials.reduce(into: [:]) { dict, serial in
            dict[serial.model, default: 0] += 1
        }
        
        // Get the top 3 models with the most serials
        let topModels = modelCounts.sorted { $0.value > $1.value }.prefix(3).map { Model(name: $0.key.name, identifier: $0.key.identifier, modelNumber: $0.key.modelNumber, serialCount: $0.value, date: $0.key.date) }
        self.topModels = topModels
    }
}

enum Timeframe: String, CaseIterable {
    case twoWeeks, month, year
}

struct DateFormatterStyle: FormatStyle {
    func format(_ value: Date) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd" // Customize the date format as needed
        return dateFormatter.string(from: value)
    }
}

#Preview {
    SerialChartView()
}

//
//  Seadmed.swift
//  Foxtronic
//
//

import Foundation
import SwiftUI

enum Device: String, CaseIterable {
    case MacBookPro = "MacBook Pro"
    case MacBookAir = "MacBook Air"
    case iMac
    case MacMini = "Mac mini"
}

struct Model: Hashable, Identifiable, Encodable, Decodable {
    var id = UUID()
    let name: String
    let identifier: String
    let modelNumber: String
    var serialCount: Int = 0
    let date: Date // Add a Date property to the Model struct

    enum CodingKeys: String, CodingKey {
         case id
         case name
         case identifier
         case modelNumber
         case serialCount
         case date
     }
    
    init(name: String, identifier: String, modelNumber: String, serialCount: Int = 0, date: Date = Date()) {
        self.name = name
        self.identifier = identifier
        self.modelNumber = modelNumber
        self.serialCount = serialCount
        self.date = date // Initialize 'date' property here
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey:.id)
        try container.encode(name, forKey:.name)
        try container.encode(identifier, forKey:.identifier)
        try container.encode(modelNumber, forKey:.modelNumber)
        try container.encode(serialCount, forKey:.serialCount)
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(UUID.self, forKey:.id)
        name = try container.decode(String.self, forKey:.name)
        identifier = try container.decode(String.self, forKey:.identifier)
        modelNumber = try container.decode(String.self, forKey:.modelNumber)
        serialCount = try container.decode(Int.self, forKey:.serialCount)
        date = Date()
    }

}



class Seadmed: ObservableObject {
    static let allDevices: [Device] = [.MacBookAir, .MacBookPro, .iMac, .MacMini]
    
    static let modelInfo: [Device: [Model]] = [
        .MacBookAir: [
            Model(name: "MacBook Air 13-tolli (2018)", identifier: "MacBookAir8,1", modelNumber: "A1932"),
            Model(name: "MacBook Air 13-tolli (2019)", identifier: "MacBookAir8,2", modelNumber: "A1932"),
            Model(name: "MacBook Air 13-tolli (2020)", identifier: "MacBookAir9,1", modelNumber: "A2179")
        ],
        .MacBookPro: [
            Model(name: "MacBook Pro 13-tolli 4TBT (2018)", identifier: "MacBookPro15,2", modelNumber: "A1989"),
            Model(name: "MacBook Pro 15-tolli (2018)", identifier: "MacBookPro15,1", modelNumber: "A1990"),
            Model(name: "MacBook Pro 13-tolli 4TBT (2019)", identifier: "MacBookPro15,2", modelNumber: "A1989"),
            Model(name: "MacBook Pro 15-tolli (2019)", identifier: "MacBookPro15,3", modelNumber: "A1990"),
            Model(name: "MacBook Pro 13-tolli 2TBT (2019)", identifier: "MacBookPro15,4", modelNumber: "A2159"),
            Model(name: "MacBook Pro 16-tolli (2019)", identifier: "MacBookPro16,1", modelNumber: "A2141"),
            Model(name: "MacBook Pro 13-tolli 2TBT (2020)", identifier: "MacBookPro16,3", modelNumber: "A2289"),
            Model(name: "MacBook Pro 13-tolli 4TBT (2020)", identifier: "MacBookPro16,2", modelNumber: "A2251")
        ],
        .iMac: [
            Model(name: "iMac Pro (2017)", identifier: "iMacPro1,1", modelNumber: "A1862"),
            Model(name: "iMac Retina 5K, 27-tolli (2020)", identifier: "iMac20,2", modelNumber: "A2115")
        ],
        .MacMini: [
            Model(name: "Mac Mini (2018)", identifier: "Macmini8,1", modelNumber: "A1993")
        ]
    ]

    static let mudeliKohatäide = ""
    
    static func saadavadMudelid(for device: Device) -> [Model] {
        return modelInfo[device] ?? []
    }

    static func saaMudeliNimi(for identifier: String) -> String? {
        return allDevices
            .flatMap { modelInfo[$0] ?? [] }
            .first { $0.identifier == identifier }?.name
    }
}


Help me fix the SerialChartView, at the moment the linear chart is not showing the devices as expected