//
//  ConnectionHomeInfoPreviewView.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 ConnectionHomeInfoPreviewView: View {
    let meter: Meter

    var body: some View {
        VStack(spacing: 14) {
            MeterInfoCard(title: "Overview", tint: meter.color) {
                MeterInfoRow(label: "Name", value: meter.name)
                MeterInfoRow(label: "Device Model", value: meter.deviceModelName)
                MeterInfoRow(label: "Advertised Model", value: meter.modelString)
                MeterInfoRow(label: "MAC", value: meter.btSerial.macAddress.description)
                if meter.modelNumber != 0 {
                    MeterInfoRow(label: "Model Identifier", value: "\(meter.modelNumber)")
                }
                MeterInfoRow(label: "Working Voltage", value: meter.documentedWorkingVoltage)
                MeterInfoRow(label: "Temperature Unit", value: meter.temperatureUnitDescription)
                MeterInfoRow(label: "Last Seen", value: meterHistoryText(for: meter.lastSeen))
                MeterInfoRow(label: "Last Connected", value: meterHistoryText(for: meter.lastConnectedAt))
            }

            MeterInfoCard(title: "Live Device Details", tint: .indigo) {
                if meter.operationalState == .dataIsAvailable {
                    if !meter.firmwareVersion.isEmpty {
                        MeterInfoRow(label: "Firmware", value: meter.firmwareVersion)
                    }
                    if meter.supportsChargerDetection {
                        MeterInfoRow(label: "Detected Charger", value: meter.chargerTypeDescription)
                    }
                    if meter.serialNumber != 0 {
                        MeterInfoRow(label: "Serial", value: "\(meter.serialNumber)")
                    }
                    if meter.bootCount != 0 {
                        MeterInfoRow(label: "Boot Count", value: "\(meter.bootCount)")
                    }
                } else {
                    Text("Connect to the meter to load firmware, serial, and boot details.")
                        .font(.footnote)
                        .foregroundColor(.secondary)
                }
            }
        }
        .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")
    }
}
