import UIKit
import AdViewSDK
import AppLovinMediationAdViewAdapter
import AppLovinSDK

fileprivate let nativeStoredImpression = "POSID06zhclyweype"
fileprivate let maxRenderingNativeAdUnitId = "c7e82db66cc5ce85"

class MAXNativeViewController: BannerBaseViewController, MANativeAdDelegate {

    private var maxMediationNativeAdUnit: MediationNativeAdUnit!
    private var maxMediationDelegate: AdViewMAXMediationNativeUtils!
    private var maxNativeAdLoader: MANativeAdLoader!
    private weak var maxLoadedNativeAd: MAAd?
    private var nativeAdPlacementConstraints: [NSLayoutConstraint] = []

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

    deinit {
        if let ad = maxLoadedNativeAd {
            maxNativeAdLoader.destroy(ad)
        }
    }

    private func applyFeedLayout(to nativeAdView: MANativeAdView) {
        guard let iconView = nativeAdView.viewWithTag(1) as? UIImageView,
              let titleLabel = nativeAdView.viewWithTag(2) as? UILabel,
              let bodyLabel = nativeAdView.viewWithTag(3) as? UILabel,
              let sponsoredLabel = nativeAdView.viewWithTag(4) as? UILabel,
              let callToActionButton = nativeAdView.viewWithTag(5) as? UIButton,
              let mainImageView = nativeAdView.viewWithTag(123) else {
            return
        }

        NativeFeedLayout.apply(
            container: nativeAdView,
            iconView: iconView,
            titleLabel: titleLabel,
            bodyLabel: bodyLabel,
            sponsoredLabel: sponsoredLabel,
            mainImageView: mainImageView,
            callToActionButton: callToActionButton,
            edgeInsets: .zero,
            useSafeArea: false
        )
    }

    func createAd() {
        maxNativeAdLoader = MANativeAdLoader(adUnitIdentifier: maxRenderingNativeAdUnitId)
        maxNativeAdLoader.nativeAdDelegate = self

        maxMediationDelegate = AdViewMAXMediationNativeUtils(nativeAdLoader: maxNativeAdLoader)
        maxMediationNativeAdUnit = MediationNativeAdUnit(
            configId: nativeStoredImpression,
            mediationDelegate: maxMediationDelegate
        )
        
        maxMediationNativeAdUnit.setContextType(.Social)
        maxMediationNativeAdUnit.setPlacementType(.FeedContent)
        maxMediationNativeAdUnit.setContextSubType(.Social)
       
        let nib = UINib(nibName: "MAXNativeAdView", bundle: .main)
        guard let maNativeAdView = nib.instantiate(withOwner: nil).first as? MANativeAdView else {
            return
        }

        let binder = MANativeAdViewBinder { builder in
            builder.iconImageViewTag = 1
            builder.titleLabelTag = 2
            builder.bodyLabelTag = 3
            builder.advertiserLabelTag = 4
            builder.callToActionButtonTag = 5
            builder.mediaContentViewTag = 123
        }
        maNativeAdView.bindViews(with: binder)

        maxMediationNativeAdUnit.fetchDemand { [weak self] _ in
            self?.maxNativeAdLoader.loadAd(into: maNativeAdView)
        }
    }

    private func styleCallToActionButton(in nativeAdView: MANativeAdView) {
        guard let callToActionButton = nativeAdView.viewWithTag(5) as? UIButton else { return }
        let rawTitle = callToActionButton.configuration?.title ?? callToActionButton.title(for: .normal)
        var buttonConfig = callToActionButton.configuration ?? .filled()
        buttonConfig.title = NativeFeedLayout.displayCallToAction(rawTitle)
        buttonConfig.baseBackgroundColor = .systemBlue
        buttonConfig.baseForegroundColor = .white
        buttonConfig.cornerStyle = .medium
        buttonConfig.contentInsets = NSDirectionalEdgeInsets(top: 12, leading: 16, bottom: 12, trailing: 16)
        callToActionButton.configuration = buttonConfig
    }

    func didLoadNativeAd(_ nativeAdView: MANativeAdView?, for ad: MAAd) {
        if let previous = maxLoadedNativeAd {
            maxNativeAdLoader.destroy(previous)
        }
        maxLoadedNativeAd = ad

        guard let nativeAdView else { return }

        applyFeedLayout(to: nativeAdView)
        styleCallToActionButton(in: nativeAdView)

        bannerView.isHidden = true
        nativeAdView.translatesAutoresizingMaskIntoConstraints = false
        if nativeAdView.superview !== view {
            nativeAdView.removeFromSuperview()
            view.addSubview(nativeAdView)
        }

        if nativeAdPlacementConstraints.isEmpty {
            nativeAdPlacementConstraints = [
                nativeAdView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15),
                nativeAdView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 15),
                nativeAdView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -15)
            ]
            NSLayoutConstraint.activate(nativeAdPlacementConstraints)
        }
    }

    func didFailToLoadNativeAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
        AdViewDemoLogger.shared.error("\(error.message)")
    }

    func didClickNativeAd(_ ad: MAAd) {}
}
