package com.all.pdfreader.pdf.reader.ui.dialog

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import com.all.pdfreader.pdf.reader.R
import com.all.pdfreader.pdf.reader.ad.AdsInsUtil
import com.all.pdfreader.pdf.reader.ad.NativeAdCache
import com.all.pdfreader.pdf.reader.databinding.AdAdmobNativeExitLayoutBinding
import com.all.pdfreader.pdf.reader.databinding.DialogExitBinding
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class ExitDialogFragment() : BottomSheetDialogFragment() {
    var onExitClick: (() -> Unit)? = null
    private lateinit var binding: DialogExitBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (savedInstanceState != null) {
            dismissAllowingStateLoss()
            return
        }
        setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        if (savedInstanceState != null) return null

        binding = DialogExitBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun show(manager: FragmentManager, tag: String?) {
        if (!manager.isStateSaved) {
            super.show(manager, tag)
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            ?.setBackgroundResource(R.drawable.dr_rc_top_12_bg_white)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupOnClick()
        val cached = NativeAdCache.getAd()
        if (cached != null) {
            Log.d(AdsInsUtil.Placement.TAG, "使用缓存广告")
            showNativeAd(cached)
        } else {
            Log.d(AdsInsUtil.Placement.TAG, "无缓存，开始加载")
            loadNativeAd()
        }
    }

    private fun setupOnClick() {
        binding.exitBtn.setOnClickListener {
            onExitClick?.invoke()
            dismiss()
        }
    }

    private fun showNativeAd(nativeAd: NativeAd) {
        if (!isAdded || activity == null) {
            nativeAd.destroy()
            return
        }

        if (requireActivity().isFinishing || requireActivity().isDestroyed) {
            nativeAd.destroy()
            return
        }

        // Inflate 必须在主线程
        val adBinding = AdAdmobNativeExitLayoutBinding.inflate(layoutInflater)
        populateNativeAdView(nativeAd, adBinding)

        binding.adFl.removeAllViews()
        binding.adFl.addView(adBinding.root)
    }

    private fun loadNativeAd() {

        NativeAdCache.load(requireActivity(), AdsInsUtil.AdPlacement.NATIVE_AND_EXIT, onAdLoaded = {
            if (!isAdded) return@load
            val ad = NativeAdCache.getAd() ?: return@load
            showNativeAd(ad)
        })
    }

    private fun populateNativeAdView(
        nativeAd: NativeAd,
        unifiedAdBinding: AdAdmobNativeExitLayoutBinding
    ) {
        val nativeAdView = unifiedAdBinding.root

        // Set the media view.
        nativeAdView.mediaView = unifiedAdBinding.adMedia

        // Set other ad assets.
        nativeAdView.headlineView = unifiedAdBinding.adHeadline
        nativeAdView.bodyView = unifiedAdBinding.adBody
        nativeAdView.callToActionView = unifiedAdBinding.adCallToAction
        nativeAdView.iconView = unifiedAdBinding.adAppIcon
//        nativeAdView.priceView = unifiedAdBinding.adPrice
        nativeAdView.starRatingView = unifiedAdBinding.adStars
//        nativeAdView.storeView = unifiedAdBinding.adStore
        nativeAdView.advertiserView = unifiedAdBinding.adAdvertiser

        // The headline and media content are guaranteed to be in every UnifiedNativeAd.
        unifiedAdBinding.adHeadline.text = nativeAd.headline
        nativeAd.mediaContent?.let { unifiedAdBinding.adMedia.setMediaContent(it) }

        // These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
        // check before trying to display them.
        if (nativeAd.body == null) {
            unifiedAdBinding.adBody.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adBody.visibility = View.VISIBLE
            unifiedAdBinding.adBody.text = nativeAd.body
        }

        if (nativeAd.callToAction == null) {
            unifiedAdBinding.adCallToAction.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adCallToAction.visibility = View.VISIBLE
            unifiedAdBinding.adCallToAction.text = nativeAd.callToAction
        }

        if (nativeAd.icon == null) {
            unifiedAdBinding.adAppIcon.visibility = View.GONE
        } else {
            unifiedAdBinding.adAppIcon.setImageDrawable(nativeAd.icon?.drawable)
            unifiedAdBinding.adAppIcon.visibility = View.VISIBLE
        }

//        if (nativeAd.price == null) {
//            unifiedAdBinding.adPrice.visibility = View.INVISIBLE
//        } else {
//            unifiedAdBinding.adPrice.visibility = View.VISIBLE
//            unifiedAdBinding.adPrice.text = nativeAd.price
//        }
//
//        if (nativeAd.store == null) {
//            unifiedAdBinding.adStore.visibility = View.INVISIBLE
//        } else {
//            unifiedAdBinding.adStore.visibility = View.VISIBLE
//            unifiedAdBinding.adStore.text = nativeAd.store
//        }

        if (nativeAd.starRating == null) {
            unifiedAdBinding.adStars.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adStars.rating = nativeAd.starRating!!.toFloat()
            unifiedAdBinding.adStars.visibility = View.VISIBLE
        }

        if (nativeAd.advertiser == null) {
            unifiedAdBinding.adAdvertiser.visibility = View.INVISIBLE
        } else {
            unifiedAdBinding.adAdvertiser.text = nativeAd.advertiser
            unifiedAdBinding.adAdvertiser.visibility = View.VISIBLE
        }

        // This method tells the Google Mobile Ads SDK that you have finished populating your
        // native ad view with this native ad.
        nativeAdView.setNativeAd(nativeAd)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 销毁广告，避免内存泄漏
        NativeAdCache.clear()
    }
}
