//
//  ChargedDeviceLibraryRowView.swift
//  USB Meter
//
//  Created by Codex on 22/04/2026.
//

import SwiftUI

struct ChargedDeviceLibraryRowView: View {
    let chargedDevice: ChargedDeviceSummary
    let isSelected: Bool

    var body: some View {
        HStack(alignment: .top, spacing: 14) {
            ChargedDeviceQRCodeView(qrIdentifier: chargedDevice.qrIdentifier, side: 58)

            VStack(alignment: .leading, spacing: 6) {
                header
                summaryText
            }
        }
        .padding(.vertical, 4)
    }

    private var header: some View {
        HStack {
            ChargedDeviceIdentityLabelView(
                chargedDevice: chargedDevice,
                iconPointSize: 17
            )
            .font(.headline)
            .foregroundColor(.primary)

            Spacer()

            if isSelected {
                Image(systemName: "checkmark.circle.fill")
                    .foregroundColor(.green)
            }
        }
    }

    @ViewBuilder
    private var summaryText: some View {
        Text(chargedDevice.identityTitle)
            .font(.caption.weight(.semibold))
            .foregroundColor(.secondary)

        if chargedDevice.isCharger {
            chargerSummaryText
        } else {
            deviceSummaryText
        }
    }

    @ViewBuilder
    private var chargerSummaryText: some View {
        if !chargedDevice.chargerObservedVoltageSelections.isEmpty {
            Text(chargedDevice.chargerObservedVoltageSelections.map { "\($0.format(decimalDigits: 1)) V" }.joined(separator: ", "))
                .font(.caption2)
                .foregroundColor(.secondary)
        } else if let chargerMaximumPowerWatts = chargedDevice.chargerMaximumPowerWatts {
            Text("Max power: \(chargerMaximumPowerWatts.format(decimalDigits: 2)) W")
                .font(.caption2)
                .foregroundColor(.secondary)
        } else {
            Text("Wireless charger")
                .font(.caption2)
                .foregroundColor(.secondary)
        }
    }

    @ViewBuilder
    private var deviceSummaryText: some View {
        Text(chargedDevice.supportedChargingModes.map(\.title).joined(separator: " + "))
            .font(.caption2)
            .foregroundColor(.secondary)

        if let capacity = chargedDevice.estimatedBatteryCapacityWh {
            Text("Estimated capacity: \(capacity.format(decimalDigits: 2)) Wh")
                .font(.caption)
                .foregroundColor(.secondary)
        }

        if let minimumCurrent = chargedDevice.minimumCurrentAmps {
            Text("Completion current: \(minimumCurrent.format(decimalDigits: 2)) A")
                .font(.caption2)
                .foregroundColor(.secondary)
        }
    }
}
