package com.remax.bill.ui.pangle

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAd
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAdData
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAdInteractionListener
import com.bumptech.glide.Glide
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGNativeAdInteractionCallback
import com.bytedance.sdk.openadsdk.api.nativeAd.PAGViewBinder
import com.remax.bill.R
import com.remax.bill.ads.log.AdLogger
import java.util.ArrayList

/**
 * Pangle原生广告UI视图组件
 * 封装Pangle原生广告的布局创建和数据绑定逻辑
 */
class PangleNativeAdView {

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

    /**
     * 创建并绑定Pangle原生广告视图到容器中
     * @param context 上下文
     * @param container 目标容器（根视图）
     * @param nativeAd Pangle原生广告对象
     * @param style 广告样式，默认为标准样式
     * @param clickViews 需要注册普通点击事件的View集合（可选）
     * @param creativeViews 需要注册创意点击事件的View集合（可选）
     * @param dislikeView 自定义关闭View（可选）
     * @return 是否绑定成功
     */
    fun bindNativeAdToContainer(
        context: Context,
        container: ViewGroup,
        nativeAd: PAGNativeAd,
        @Suppress("UNUSED_PARAMETER") style: PangleNativeAdStyle = PangleNativeAdStyle.STANDARD,
        clickViews: List<View>? = null,
        dislikeView: View? = null,
        interactionListener: PAGNativeAdInteractionCallback? = null
    ): Boolean {
        return try {
            // 清空容器
            container.removeAllViews()

            // 创建原生广告布局
            val adView = createNativeAdLayout(context, style)

            // 获取广告数据
            val nativeAdData = nativeAd.getNativeAdData()

            // 绑定广告数据
            bindNativeAdData(context, adView, nativeAdData)

            // 添加到容器
            container.addView(adView)

            // 注册交互视图和回调（必须在显示前调用）
            val clickViewsList = ArrayList<View>().apply {
                clickViews?.forEach { add(it) }
                // 如果没有指定，默认将标题、描述、按钮、图标添加到点击视图
                if (clickViews.isNullOrEmpty()) {
                    adView.findViewById<TextView>(R.id.tv_ad_title)?.let { add(it) }
                    adView.findViewById<TextView>(R.id.tv_ad_description)?.let { add(it) }
                    adView.findViewById<TextView>(R.id.btn_ad_cta)?.let { add(it) }
                    adView.findViewById<ImageView>(R.id.iv_ad_icon)?.let { add(it) }
                }
            }

            val binder = PAGViewBinder.Builder(container)
                .titleTextView(adView.findViewById<TextView>(R.id.tv_ad_title))
                .descriptionTextView( adView.findViewById<TextView>(R.id.tv_ad_description))
                .logoViewGroup(adView.findViewById<FrameLayout>(R.id.fl_ad_logo))
                .iconImageView(adView.findViewById<ImageView>(R.id.iv_ad_icon))
                .dislikeView(dislikeView)
                .build()
            @Suppress("UNCHECKED_CAST")
            nativeAd.registerViewForInteraction(
                binder,
                clickViewsList as MutableList<View>,
                interactionListener
            )

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

    /**
     * 创建原生广告布局
     */
    private fun createNativeAdLayout(
        context: Context,
        style: PangleNativeAdStyle
    ): ViewGroup {
        return LayoutInflater.from(context)
            .inflate(style.layoutResId, null) as ViewGroup
    }

    /**
     * 绑定Pangle原生广告数据到视图
     */
    private fun bindNativeAdData(
        context: Context,
        adView: ViewGroup,
        nativeAdData: PAGNativeAdData
    ) {
        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)
            val logoContainer = adView.findViewById<FrameLayout>(R.id.fl_ad_logo)

            // 设置广告标题
            titleView?.text = nativeAdData.title ?: ""

            // 设置CTA按钮
            ctaButton?.text = nativeAdData.buttonText ?: "INSTALL"

            // 设置广告描述
            descView?.text = nativeAdData.description ?: ""

            // 设置图标
            nativeAdData.icon?.let { icon ->
                loadImage(context, icon.imageUrl, iconView)
                iconView?.visibility = View.VISIBLE
            } ?: run {
                iconView?.visibility = View.GONE
            }

            // ad logo
            logoContainer?.let { container ->
                container.removeAllViews()
                nativeAdData.adLogoView?.let { logoView ->
                    container.addView(logoView)
                    container.visibility = View.VISIBLE
                } ?: run {
                    container.visibility = View.GONE
                }
            }

            AdLogger.d("Pangle原生广告数据绑定完成")

        } catch (e: Exception) {
            AdLogger.e("绑定Pangle原生广告数据失败", e)
        }
    }

    /**
     * 加载图片（使用Glide）
     */
    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("加载Pangle原生广告图片失败: $imageUrl", e)
        }
    }

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