//
//  MeterOverviewSectionView.swift
//  USB Meter
//
//  Created by Bogdan Timofte on 29/03/2026.
//  Co-authored-by: GPT-5.3-Codex.
//  Copyright © 2026 Bogdan Timofte. All rights reserved.
//

import SwiftUI

struct MeterOverviewSectionView: View {
    let meter: Meter

    private var overviewInfoMessage: String? {
        guard meter.operationalState != .dataIsAvailable else {
            return nil
        }
        return "Connect to the meter to load firmware, serial, and boot details."
    }

    var body: some View {
        VStack(spacing: 14) {
            MeterInfoCardView(
                title: "Overview",
                infoMessage: overviewInfoMessage,
                tint: meter.color
            ) {
                MeterInfoRowView(label: "Name", value: meter.name)
                MeterInfoRowView(label: "Device Model", value: meter.deviceModelName)
                MeterInfoRowView(label: "Advertised Model", value: meter.modelString)
                MeterInfoRowView(label: "MAC", value: meter.btSerial.macAddress.description)
                if meter.modelNumber != 0 {
                    MeterInfoRowView(label: "Model Identifier", value: "\(meter.modelNumber)")
                }
                MeterInfoRowView(label: "Working Voltage", value: meter.documentedWorkingVoltage)
                MeterInfoRowView(label: "Temperature Unit", value: meter.temperatureUnitDescription)
                MeterInfoRowView(label: "Last Seen", value: meterHistoryText(for: meter.lastSeen))
                MeterInfoRowView(label: "Last Connected", value: meterHistoryText(for: meter.lastConnectedAt))
                if meter.operationalState == .dataIsAvailable {
                    if !meter.firmwareVersion.isEmpty {
                        MeterInfoRowView(label: "Firmware", value: meter.firmwareVersion)
                    }
                    if meter.serialNumber != 0 {
                        MeterInfoRowView(label: "Serial", value: "\(meter.serialNumber)")
                    }
                    if meter.bootCount != 0 {
                        MeterInfoRowView(label: "Boot Count", value: "\(meter.bootCount)")
                    }
                }
            }

        }
        .padding(.horizontal, 12)
    }

    private func meterHistoryText(for date: Date?) -> String {
        guard let date else {
            return "Never"
        }
        return date.format(as: "yyyy-MM-dd HH:mm")
    }
}
