package com.remax.bill.ui.topon

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import com.bumptech.glide.Glide
import com.remax.bill.R
import com.remax.bill.ads.log.AdLogger
import com.thinkup.nativead.api.NativeAd
import com.thinkup.nativead.api.TUNativeAdView
import com.thinkup.nativead.api.TUNativeMaterial
import com.thinkup.nativead.api.TUNativePrepareInfo

/**
 * TopOn全屏原生广告视图组件
 * 提供全屏原生广告的布局创建、数据绑定和交互注册
 */
class ToponFullScreenNativeAdView {

    companion object {
        private const val TAG = "ToponFullScreenNativeAdView"
    }

    /**
     * 创建并绑定全屏原生广告视图到容器中
     */
    fun bindFullScreenNativeAdToContainer(
        context: Context,
        container: ViewGroup,
        nativeAd: NativeAd,
        lifecycleOwner: LifecycleOwner
    ): Boolean {
        return try {
            container.removeAllViews()

            val isNativeExpress = nativeAd.isNativeExpress()
            if (isNativeExpress) {
                bindTemplateAd(context, container, nativeAd)
            } else {
                bindSelfRenderAd(context, container, nativeAd)
            }

            AdLogger.d("TopOn全屏原生广告视图绑定成功")
            true
        } catch (e: Exception) {
            AdLogger.e("TopOn全屏原生广告视图绑定失败", e)
            false
        }
    }

    /**
     * 创建加载视图
     */
    fun createFullScreenLoadingView(context: Context, container: ViewGroup) {
        try {
            container.removeAllViews()
            val loadingView = LayoutInflater.from(context)
                .inflate(R.layout.layout_fullscreen_loading, container, false)
            container.addView(loadingView)
        } catch (e: Exception) {
            AdLogger.e("TopOn全屏原生加载视图创建失败", e)
        }
    }

    /**
     * 绑定模板渲染广告
     */
    private fun bindTemplateAd(
        context: Context,
        container: ViewGroup,
        nativeAd: NativeAd
    ) {
        try {
            val nativeAdView = TUNativeAdView(context)
            nativeAd.renderAdContainer(nativeAdView, null)
            nativeAd.prepare(nativeAdView, null)
            container.addView(nativeAdView)
            AdLogger.d("TopOn全屏模板渲染广告绑定完成")
        } catch (e: Exception) {
            AdLogger.e("TopOn全屏模板渲染广告绑定失败", e)
            throw e
        }
    }

    /**
     * 绑定自渲染广告
     */
    private fun bindSelfRenderAd(
        context: Context,
        container: ViewGroup,
        nativeAd: NativeAd
    ) {
        try {
            val adView = createFullScreenNativeAdLayout(context)
            val nativeAdView = TUNativeAdView(context)
            val material = nativeAd.getAdMaterial()
            bindNativeAdData(adView, material)
            val prepareInfo = createPrepareInfo(adView)
            nativeAd.renderAdContainer(nativeAdView, adView)
            nativeAd.prepare(nativeAdView, prepareInfo)
            container.addView(nativeAdView)
            AdLogger.d("TopOn全屏自渲染广告绑定完成")
        } catch (e: Exception) {
            AdLogger.e("TopOn全屏自渲染广告绑定失败", e)
            throw e
        }
    }

    /**
     * 创建全屏原生广告布局
     */
    private fun createFullScreenNativeAdLayout(context: Context): ViewGroup {
        return LayoutInflater.from(context)
            .inflate(R.layout.layout_topon_fullscreen_native_ad, null) as ViewGroup
    }

    /**
     * 创建 PrepareInfo
     */
    private fun createPrepareInfo(adView: ViewGroup): TUNativePrepareInfo {
        val prepareInfo = TUNativePrepareInfo()
        adView.findViewById<TextView>(R.id.tv_ad_title)?.let {
            prepareInfo.setTitleView(it)
        }
        adView.findViewById<TextView>(R.id.tv_ad_description)?.let {
            prepareInfo.descView = it
        }
        adView.findViewById<TextView>(R.id.btn_ad_cta)?.let {
            prepareInfo.ctaView = it
        }
        adView.findViewById<ImageView>(R.id.iv_ad_icon)?.let {
            prepareInfo.setIconView(it)
        }
        adView.findViewById<ViewGroup>(R.id.fl_ad_media)?.let {
            prepareInfo.setMainImageView(it)
        }
        return prepareInfo
    }

    /**
     * 绑定原生广告数据
     */
    private fun bindNativeAdData(
        adView: ViewGroup,
        material: TUNativeMaterial
    ) {
        try {
            val titleView = adView.findViewById<TextView>(R.id.tv_ad_title)
            val ctaButton = adView.findViewById<TextView>(R.id.btn_ad_cta)
            val iconView = adView.findViewById<ImageView>(R.id.iv_ad_icon)
            val descView = adView.findViewById<TextView>(R.id.tv_ad_description)

            titleView?.text = material.title ?: "Test TopOn Ads"
            ctaButton?.text = material.callToActionText ?: "INSTALL"
            descView?.text = material.descriptionText ?: ""

            material.iconImageUrl?.let { iconUrl ->
                iconView?.let { view ->
                    loadImage(view.context, iconUrl, view)
                    view.visibility = View.VISIBLE
                }
            } ?: run {
                iconView?.setImageResource(android.R.drawable.ic_menu_info_details)
                iconView?.visibility = View.VISIBLE
            }

            // 处理主图
            material.mainImageUrl?.let { mainImageUrl ->
                val mediaContainer = adView.findViewById<ViewGroup>(R.id.fl_ad_media)
                mediaContainer?.let { container ->
                    container.removeAllViews()
                    val imageView = ImageView(container.context)
                    imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                    loadImage(container.context, mainImageUrl, imageView)
                    container.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                    container.visibility = View.VISIBLE
                }
            } ?: run {
                adView.findViewById<ViewGroup>(R.id.fl_ad_media)?.visibility = View.GONE
            }

            AdLogger.d("TopOn全屏原生广告数据绑定完成")
        } catch (e: Exception) {
            AdLogger.e("绑定TopOn全屏原生广告数据失败", e)
        }
    }

    /**
     * 加载图片
     */
    private fun loadImage(context: Context, imageUrl: String?, imageView: ImageView?) {
        if (imageUrl.isNullOrEmpty() || imageView == null) {
            return
        }
        try {
            Glide.with(context)
                .load(imageUrl)
                .into(imageView)
        } catch (e: Exception) {
            AdLogger.e("加载TopOn全屏原生广告图片失败: $imageUrl", e)
        }
    }

    /**
     * 创建错误视图
     */
    fun createErrorView(context: Context, errorMessage: String? = null): View {
        return TextView(context).apply {
            text = errorMessage ?: "广告加载失败"
            textSize = 12f
            setTextColor(0xFF999999.toInt())
            gravity = android.view.Gravity.CENTER
            setPadding(16, 16, 16, 16)
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }
    }
}

