import UIKit
import AdViewSDK
import GoogleMobileAds
import AdMobAdViewAdapter

fileprivate let nativeStoredImpression = "POSID06zhclyweype"
fileprivate let admobRenderingNativeAdUnitId = "ca-app-pub-7283949697136772/5773334681"

class AdMobNativeViewController: NativeBaseViewController, NativeAdLoaderDelegate, GoogleMobileAds.NativeAdDelegate {

    private var mediationDelegate: AdViewAdMobMediationNativeUtils!
    private var admobMediationNativeAdUnit: MediationNativeAdUnit!
    private var adLoader: AdLoader?
    private let gadNativeAdView = NativeAdView()

    override func viewDidLoad() {
        super.viewDidLoad()
        applyFeedNativeLayout()
        setupNativeAdViewContainer()
        createAd()
    }

    override func loadView() {
        super.loadView()
    }

    private func setupNativeAdViewContainer() {
        gadNativeAdView.translatesAutoresizingMaskIntoConstraints = false
        gadNativeAdView.backgroundColor = .clear
        view.insertSubview(gadNativeAdView, at: 0)
        NSLayoutConstraint.activate([
            gadNativeAdView.topAnchor.constraint(equalTo: view.topAnchor),
            gadNativeAdView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            gadNativeAdView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            gadNativeAdView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }

    func createAd() {
        let gadRequest = Request()

        mediationDelegate = AdViewAdMobMediationNativeUtils(gadRequest: gadRequest)
        admobMediationNativeAdUnit = MediationNativeAdUnit(
            configId: nativeStoredImpression,
            mediationDelegate: mediationDelegate
        )
            
        admobMediationNativeAdUnit.setContextType(.Social)
        admobMediationNativeAdUnit.setPlacementType(.FeedContent)
        admobMediationNativeAdUnit.setContextSubType(.Social)
        
        admobMediationNativeAdUnit.fetchDemand { [weak self] _ in
            guard let self else { return }
            self.adLoader = AdLoader(
                adUnitID: admobRenderingNativeAdUnitId,
                rootViewController: self,
                adTypes: [.native],
                options: nil
            )
            self.adLoader?.delegate = self
            self.adLoader?.load(gadRequest)
        }
    }

    func adLoader(_ adLoader: AdLoader, didReceive nativeAd: GoogleMobileAds.NativeAd) {
        nativeAd.delegate = self

        titleLabel.text = nativeAd.headline
        bodyLabel.text = nativeAd.body
        updateCallToActionButtonTitle(nativeAd.callToAction)
        sponsoredLabel.text = nativeAd.advertiser
        iconView.image = nativeAd.icon?.image
        mainImageView.image = nativeAd.images?.first?.image
        invalidateNativeMainImageLayoutIfNeeded()

        registerNativeAdForClicks(nativeAd)
    }

    private func registerNativeAdForClicks(_ nativeAd: GoogleMobileAds.NativeAd) {
        gadNativeAdView.headlineView = titleLabel
        gadNativeAdView.bodyView = bodyLabel
        gadNativeAdView.iconView = iconView
        gadNativeAdView.callToActionView = callToActionButton
        gadNativeAdView.advertiserView = sponsoredLabel
        gadNativeAdView.imageView = mainImageView

        nativeAd.rootViewController = self
        gadNativeAdView.nativeAd = nativeAd
    }

    func adLoader(_ adLoader: AdLoader, didFailToReceiveAdWithError error: Error) {
        AdViewDemoLogger.shared.error("\(error.localizedDescription)")
    }

    func nativeAdDidRecordClick(_ nativeAd: GoogleMobileAds.NativeAd) {}
}
