package com.gem.media.ad;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.ads.cal.notes.BaseApplication;
import com.ads.cal.notes.R;
import com.gem.media.InitA;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.nativead.MediaView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;

import java.util.Locale;

/**
 * VNA 专用原生广告管理器（AdMob SDK）。
 * 与旧 AdmobNativeManager 完全隔离，仅服务于 VNA（Video Native Ad）流程。
 *
 * 调用链：core transferData(11) → MyDataService case 11 → AdManager.setData(VNA_TYPE)
 *        → VNANativeAdManager.loadVnaAd() → VNANativeAdWindManager → VNActivity
 */
public class VNANativeAdManager {
    private static final String TAG = "VNANativeAdManager";
    private static final String AD_TYPE = "admob_vna_native";

    /**
     * VNA 场景标识，与 mediaapp/max_mediaapp/pangle_mediaapp 三端统一。
     * 用于 sendNativeAdStatusMessage 中路由 message.what = 5002。
     */
    private static final String VNA_SCENARIO = "yuansheng";

    private NativeAdStatusCallBack adStatusCallBack;

    private static final class Holder {
        static final VNANativeAdManager INSTANCE = new VNANativeAdManager();
    }

    public static VNANativeAdManager getInstance() {
        return Holder.INSTANCE;
    }

    private long requestTime = -1;
    private static volatile String sAdId;
    private NativeAd mNativeAd;
    private volatile boolean isLoading;

    private volatile long lastAdRequestTime = 0;
    private static final long MIN_REQUEST_INTERVAL = 300;

    // VNA fallback 状态：视频广告位失败后尝试图文广告位
    private boolean vnaFallbackMode = false;
    private String vnaImageSlotId = "";

    /**
     * VNA 模式加载广告：从 CpAdData 获取 AdMob 原生广告位 ID。
     * 双 slotId 方案：index 0 = 视频广告位，index 1 = 图文广告位。
     */
    public void loadVnaAd() {
        vnaFallbackMode = false;
        vnaImageSlotId = "";
        AdData adData = CpAdData.getInstance().getAdData(CpAdData.CP_ADMOB);
        if (adData == null) {
            ALog.w(TAG, "loadVnaAd: CpAdData not initialized");
            return;
        }
        // index 0: 视频广告位（优先）
        String videoSlotId = adData.getAdAdId(AdData.AD_TYPE_NATIVE, 0);
        // index 1: 图文广告位（兜底）
        String imageSlotId = adData.getAdAdId(AdData.AD_TYPE_NATIVE, 1);
        vnaImageSlotId = TextUtils.isEmpty(imageSlotId) ? "" : imageSlotId;
        ALog.d(TAG, "loadVnaAd: videoSlot=" + videoSlotId + " imageSlot=" + vnaImageSlotId);

        if (TextUtils.isEmpty(videoSlotId)) {
            if (!TextUtils.isEmpty(imageSlotId)) {
                ALog.d(TAG, "loadVnaAd: no video slot, using image slot");
                sAdId = imageSlotId;
                loadAd(12);
            } else {
                ALog.w(TAG, "loadVnaAd: no native ad slot id");
            }
            return;
        }
        sAdId = videoSlotId;
        loadAd(10);
    }

    /**
     * AdMob 加载原生广告。
     * AdMob 的 AdLoader 是一次性的（每次加载创建新实例）。
     */
    private void loadAd(int trigger) {
        ALog.w(TAG, "loadAd start trigger=" + trigger);
        if (isNativeAdReady()) {
            ALog.w(TAG, "ad already ready");
            return;
        }
        if (isLoading) {
            ALog.w(TAG, "ad is loading");
            return;
        }
        if (TextUtils.isEmpty(sAdId)) {
            ALog.w(TAG, "sAdId is null");
            return;
        }
        // fallback 路径（trigger=12）跳过频率检查
        if (trigger != 12) {
            long currentTime = System.currentTimeMillis();
            if (Math.abs(currentTime - lastAdRequestTime) < MIN_REQUEST_INTERVAL) {
                ALog.w(TAG, "request too frequent");
                return;
            }
            lastAdRequestTime = currentTime;
        } else {
            lastAdRequestTime = System.currentTimeMillis();
        }

        Context context = BaseApplication.getApplication();
        if (context == null) {
            ALog.w(TAG, "loadAd: context is null");
            return;
        }

        if (null != adStatusCallBack) {
            adStatusCallBack.onAdLoad(Constants.NODE_REQUEST, AD_TYPE, sAdId, -1, sAdId, VNA_SCENARIO);
        }
        requestTime = System.currentTimeMillis();
        isLoading = true;

        try {
            // AdMob: 每次创建新的 AdLoader（一次性使用）
            AdLoader adLoader = new AdLoader.Builder(context, sAdId)
                    .forNativeAd(nativeAd -> {
                        // 加载成功
                        isLoading = false;
                        ALog.i(TAG, "onNativeAdLoaded");
                        // 销毁旧的 NativeAd
                        if (mNativeAd != null) {
                            mNativeAd.destroy();
                        }
                        mNativeAd = nativeAd;
                        requestTime = System.currentTimeMillis() - requestTime;
                        if (null != adStatusCallBack) {
                            adStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, AD_TYPE,
                                    "loaded", requestTime, sAdId, VNA_SCENARIO, "vna");
                        }
                        requestTime = System.currentTimeMillis();
                    })
                    .withAdListener(new AdListener() {
                        @Override
                        public void onAdFailedToLoad(LoadAdError loadAdError) {
                            isLoading = false;
                            String error = String.format(
                                    Locale.getDefault(),
                                    "domain: %s, code: %d, message: %s",
                                    loadAdError.getDomain(),
                                    loadAdError.getCode(),
                                    loadAdError.getMessage());
                            ALog.i(TAG, "onAdFailedToLoad: " + error);
                            requestTime = System.currentTimeMillis() - requestTime;

                            // VNA fallback: 视频广告位失败，尝试图文广告位
                            if (!vnaFallbackMode && !vnaImageSlotId.isEmpty()) {
                                ALog.d(TAG, "VNA video failed, trying image fallback");
                                vnaFallbackMode = true;
                                sAdId = vnaImageSlotId;
                                loadAd(12);
                                return;
                            }
                            if (null != adStatusCallBack) {
                                adStatusCallBack.onNoAdError(Constants.NODE_ERROR, AD_TYPE, error,
                                        requestTime, sAdId, VNA_SCENARIO);
                            }
                        }

                        @Override
                        public void onAdImpression() {
                            Log.i(TAG, "vna ad onAdImpression");
                            requestTime = System.currentTimeMillis() - requestTime;
                            if (null != adStatusCallBack) {
                                adStatusCallBack.onAdShow(Constants.NODE_SHOW, AD_TYPE, "show",
                                        requestTime, sAdId, VNA_SCENARIO);
                            }
                            // 通知 VNActivity 曝光已触发，驱动自适应关闭计时器
//                            Activity currentAct = InitA.getInstance().getCurrentActivity();
//                            if (currentAct instanceof VNActivity) {
//                                ((VNActivity) currentAct).onExposureConfirmed();
//                            }
                        }

                        @Override
                        public void onAdClicked() {
                            ALog.i(TAG, "vna ad onAdClicked");
                            if (null != adStatusCallBack) {
                                adStatusCallBack.onAdClick(Constants.NODE_CLICK, AD_TYPE, "click",
                                        -1, sAdId, VNA_SCENARIO);
                            }
                            // VNA: 点击广告后同步设置关闭原因并 finish
//                            Activity currentAct = InitA.getInstance().getCurrentActivity();
//                            if (currentAct instanceof VNActivity) {
//                                ((VNActivity) currentAct).setDismissReason(VNActivity.DISMISS_USER_CLICK);
//                                currentAct.finish();
//                            } else {
//                                VNANativeAdWindManager.getInstance().removeNativeAd();
//                            }
                        }
                    })
                    .build();

            adLoader.loadAd(new AdRequest.Builder().build());
            ALog.w(TAG, "loadAd done");
        } catch (Exception e) {
            isLoading = false;
            ALog.e(TAG, "loadAd exception: " + e.getMessage());
        }
    }

    public boolean isNativeAdReady() {
        return mNativeAd != null;
    }

    /**
     * 展示 VNA 广告。在 VNActivity 中调用。
     * @param nativeAdView AdMob NativeAdView 容器
     * @return 0=成功, 负数=失败
     */
    public int showAd(NativeAdView nativeAdView) {
        if (!isNativeAdReady()) {
            return -1;
        }
        ALog.i(TAG, "showAd");

        try {
            bindNativeAdView(nativeAdView, mNativeAd);
            nativeAdView.setNativeAd(mNativeAd);
        } catch (Exception e) {
            ALog.e(TAG, "showAd render error: " + e.getMessage());
            return -3;
        }

        nativeAdView.setVisibility(View.VISIBLE);
        ALog.i(TAG, "showAd end");
        return 0;
    }

    /**
     * 绑定 NativeAd 素材到 NativeAdView。
     * View ID 与 vna_n_layout.xml 一致。
     */
    private void bindNativeAdView(NativeAdView adView, NativeAd nativeAd) {
        // Set the media view
        MediaView mediaView = adView.findViewById(R.id.vna_ad_media);
        adView.setMediaView(mediaView);

        // Set other ad assets
        adView.setHeadlineView(adView.findViewById(R.id.vna_ad_headline));
        adView.setBodyView(adView.findViewById(R.id.vna_ad_body));
        adView.setCallToActionView(adView.findViewById(R.id.vna_ad_call_to_action));
        adView.setIconView(adView.findViewById(R.id.vna_ad_icon));
        adView.setPriceView(adView.findViewById(R.id.vna_ad_price));
        adView.setStarRatingView(adView.findViewById(R.id.vna_ad_stars));
        adView.setStoreView(adView.findViewById(R.id.vna_ad_store));
        adView.setAdvertiserView(adView.findViewById(R.id.vna_ad_advertiser));

        // headline and mediaContent are guaranteed in every NativeAd
        ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
        if (mediaView != null && nativeAd.getMediaContent() != null) {
            mediaView.setMediaContent(nativeAd.getMediaContent());
        }

        // These assets aren't guaranteed, check before displaying
        if (nativeAd.getBody() == null) {
            adView.getBodyView().setVisibility(View.INVISIBLE);
        } else {
            adView.getBodyView().setVisibility(View.VISIBLE);
            ((TextView) adView.getBodyView()).setText(nativeAd.getBody());
        }

        if (nativeAd.getCallToAction() == null) {
            adView.getCallToActionView().setVisibility(View.INVISIBLE);
        } else {
            adView.getCallToActionView().setVisibility(View.VISIBLE);
            ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
        }

        if (nativeAd.getIcon() == null) {
            adView.getIconView().setVisibility(View.GONE);
        } else {
            ((ImageView) adView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable());
            adView.getIconView().setVisibility(View.VISIBLE);
        }

        if (nativeAd.getPrice() == null) {
            adView.getPriceView().setVisibility(View.INVISIBLE);
        } else {
            adView.getPriceView().setVisibility(View.VISIBLE);
            ((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
        }

        if (nativeAd.getStore() == null) {
            adView.getStoreView().setVisibility(View.INVISIBLE);
        } else {
            adView.getStoreView().setVisibility(View.VISIBLE);
            ((TextView) adView.getStoreView()).setText(nativeAd.getStore());
        }

        if (nativeAd.getStarRating() == null) {
            adView.getStarRatingView().setVisibility(View.INVISIBLE);
        } else {
            ((RatingBar) adView.getStarRatingView()).setRating(nativeAd.getStarRating().floatValue());
            adView.getStarRatingView().setVisibility(View.VISIBLE);
        }

        if (nativeAd.getAdvertiser() == null) {
            adView.getAdvertiserView().setVisibility(View.INVISIBLE);
        } else {
            ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
            adView.getAdvertiserView().setVisibility(View.VISIBLE);
        }
    }

    public void destroyAd() {
        if (mNativeAd != null) {
            mNativeAd.destroy();
            mNativeAd = null;
        }
        VNANativeAdWindManager.getInstance().removeNativeAd();
    }

    public void setAdStatusCallBack(NativeAdStatusCallBack adStatusCallBack) {
        this.adStatusCallBack = adStatusCallBack;
    }
}
