//
//  ChargedDeviceQRCodeView.swift
//  USB Meter
//
//  Created by Codex on 10/04/2026.
//

import CoreImage.CIFilterBuiltins
import SwiftUI

struct ChargedDeviceQRCodeView: View {
    let qrIdentifier: String
    let side: CGFloat

    private let context = CIContext()
    private let filter = CIFilter.qrCodeGenerator()

    var body: some View {
        Group {
            if let image = qrImage {
                Image(uiImage: image)
                    .interpolation(.none)
                    .resizable()
                    .scaledToFit()
            } else {
                RoundedRectangle(cornerRadius: 14)
                    .fill(Color.secondary.opacity(0.12))
                    .overlay(
                        Image(systemName: "qrcode")
                            .font(.system(size: side * 0.34, weight: .semibold))
                            .foregroundColor(.secondary)
                    )
            }
        }
        .frame(width: side, height: side)
        .padding(8)
        .background(
            RoundedRectangle(cornerRadius: 18)
                .fill(Color.white.opacity(0.92))
        )
    }

    private var qrImage: UIImage? {
        filter.setValue(Data(qrIdentifier.utf8), forKey: "inputMessage")
        filter.correctionLevel = "M"

        guard let outputImage = filter.outputImage else {
            return nil
        }

        let transform = CGAffineTransform(scaleX: 12, y: 12)
        let scaledImage = outputImage.transformed(by: transform)

        guard let cgImage = context.createCGImage(scaledImage, from: scaledImage.extent) else {
            return nil
        }

        return UIImage(cgImage: cgImage)
    }
}
