//
//  ImageTVC.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 06/05/25.
//

import UIKit
import AVFoundation
class ImageTVC: UITableViewCell {

    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    @IBOutlet weak var displayImageView: UIImageView!
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    @IBOutlet var gifView: UIImageView!
    @IBOutlet weak var cameraView: CustomView!
    @IBOutlet weak var cameraTitleLabel: UILabel!
    @IBOutlet weak var cameraDescLabel: UILabel!
    
    @IBOutlet var ic_green_arrow: UIImageView!
    var scannerView: QRScannerView!
    override func awakeFromNib() {
        super.awakeFromNib()
        gifView.isHidden = true
        ic_green_arrow.image = loadImage(named: "ic_green_arrow")
        // Initialization code
        cameraTitleLabel.text = "GoodFlip requires camera permission to scan the QR and connect with the sensor"
        
        cameraTitleLabel.font = FontManager.font(ofSize: 14, weight: .medium)
        
        cameraTitleLabel.textColor = .white
        
        let first = "Provide Camera Permissions"

        let attributedString = NSMutableAttributedString(string: first, attributes: [
            .font: FontManager.font(ofSize: 16, weight: .semibold),
            .foregroundColor: CustomColor.shared.lightGreen,
            .underlineStyle: NSUnderlineStyle.single.rawValue,
        ])

        cameraDescLabel.attributedText = attributedString
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    func setupQRView() {
        scannerView = QRScannerView(frame: cameraView.bounds)
        scannerView.onCodeDetected = { code in
            print("Detected QR Code: \(code)")
            // You can stop scanning or navigate
            self.scannerView.stopScanning()
        }
        
        cameraView.addSubview(scannerView)
    }
    
}

class QRScannerView: UIView {

    private let captureSession = AVCaptureSession()
    private var previewLayer: AVCaptureVideoPreviewLayer!
    var onCodeDetected: ((String) -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCamera()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupCamera()
    }

    private func setupCamera() {
        guard let videoCaptureDevice = AVCaptureDevice.default(for: .video),
              let videoInput = try? AVCaptureDeviceInput(device: videoCaptureDevice),
              captureSession.canAddInput(videoInput) else {
            print("Failed to set up camera input")
            return
        }

        captureSession.addInput(videoInput)

        let metadataOutput = AVCaptureMetadataOutput()
        if captureSession.canAddOutput(metadataOutput) {
            captureSession.addOutput(metadataOutput)

            metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            metadataOutput.metadataObjectTypes = [.qr]
        }

        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer.frame = layer.bounds
        previewLayer.videoGravity = .resizeAspectFill
        layer.addSublayer(previewLayer)

        self.captureSession.startRunning()
    }

    func stopScanning() {
        captureSession.stopRunning()
    }

    func startScanning() {
        if !captureSession.isRunning {
            captureSession.startRunning()
        }
    }
}

extension QRScannerView: AVCaptureMetadataOutputObjectsDelegate {
    func metadataOutput(_ output: AVCaptureMetadataOutput,
                        didOutput metadataObjects: [AVMetadataObject],
                        from connection: AVCaptureConnection) {
        if let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject,
           metadataObject.type == .qr,
           let stringValue = metadataObject.stringValue {
            onCodeDetected?(stringValue)
        }
    }
}
