using System;
using System.Collections.Generic;
using AnyThinkAds.Api;
using AnyThinkAds.Common;
using AnyThinkAds.ThirdParty.LitJson;
using Runtime.ADAggregator;
using UnityEngine;

public class InteractionPlayer : ADPlayer, ATInterstitialAdListener
{
    private IATInterstitialAdClient _client;
    private ADListenerAggregator _aggregator;
    private bool _autoLoadRegistered;

    public override void OnInit()
    {
        _client = AnyThinkAds.ATAdsClientFactory.BuildInterstitialAdClient();
        _aggregator = new ADListenerAggregator();
        _aggregator.BindInterstitialAdListener(_client, this);
    }

    public override void ShowAD(Action onClose, Action<bool> onVideoComplete)
    {
        if (!IsReadly())
        {
            return;
        }

        adListener.onClose = onClose;
        adListener.onVideoComplete = onVideoComplete;
        var mapJson = JsonMapper.ToJson(BuildInterstitialExtra());

        if (UseAutoLoad())
        {
            EnsureAutoLoadRegistered();
            _client.showAutoAd(Key, mapJson);
        }
        else
        {
            _client.showInterstitialAd(Key, mapJson);
        }

        curState = 0;
    }

    public override bool IsReadly()
    {
        if (curState == 2)
        {
            return true;
        }

        if (UseAutoLoad())
        {
            if (_client != null && _client.autoLoadInterstitialAdReadyForPlacementID(Key))
            {
                curState = 2;
                return true;
            }

            return false;
        }

        if (_client != null && _client.hasInterstitialAdReady(Key))
        {
            curState = 2;
            return true;
        }

        return false;
    }

    public override void LoadAD()
    {
        if (curState != 0)
        {
            return;
        }

        if (UseAutoLoad())
        {
            EnsureAutoLoadRegistered();
            _client.setAutoLocalExtra(Key, JsonMapper.ToJson(BuildInterstitialExtra()));
            curState = _client.autoLoadInterstitialAdReadyForPlacementID(Key) ? 2 : 1;
            return;
        }

        if (_client != null && _client.hasInterstitialAdReady(Key))
        {
            curState = 2;
            return;
        }

        var jsonmap = new Dictionary<string, object>();
        var width = (int)(Screen.width * 0.7f);
        var atSize = new ATSize(width, (int)(width * 1.5f));
        jsonmap.Add(ATInterstitialAdLoadingExtra.kATInterstitialAdLoadingExtraInterstitialAdSizeStruct, atSize);
        curState = 1;
        _client.loadInterstitialAd(Key, JsonMapper.ToJson(jsonmap));
    }

    public void onInterstitialAdLoad(string placementId)
    {
        Debug.Log($"[Topon] Interstitial loaded. placementId={placementId}");
        curState = 2;
    }

    public void onInterstitialAdLoadFail(string placementId, string code, string message)
    {
        Debug.LogError($"插屏加载失败: {message} , code:{code} , placementId: {placementId}");
        curState = 0;
    }

    public void onInterstitialAdShow(string placementId, ATCallbackInfo callbackInfo)
    {
        Debug.Log($"[Topon] Interstitial show. placementId={placementId}");
        NotifyShowStarted();
    }

    public void onInterstitialAdFailedToShow(string placementId)
    {
        curState = 0;
        adListener.OnShowError();
    }

    public void onInterstitialAdClose(string placementId, ATCallbackInfo callbackInfo)
    {
        Debug.Log($"[Topon] Interstitial close. placementId={placementId}");
        adListener.OnAdClose();
        adListener.OnShowComplete();
    }

    public void onInterstitialAdClick(string placementId, ATCallbackInfo callbackInfo)
    {
        Debug.Log($"[Topon] Interstitial clicked. placementId={placementId}");
    }

    public void onInterstitialAdStartPlayingVideo(string placementId, ATCallbackInfo callbackInfo)
    {
        Debug.Log($"[Topon] Interstitial video start. placementId={placementId}");
    }

    public void onInterstitialAdEndPlayingVideo(string placementId, ATCallbackInfo callbackInfo)
    {
        Debug.Log($"[Topon] Interstitial video end. placementId={placementId}");
    }

    public void onInterstitialAdFailedToPlayVideo(string placementId, string code, string message)
    {
        curState = 0;
        adListener.OnShowError();
    }

    public void startLoadingADSource(string placementId, ATCallbackInfo callbackInfo)
    {
    }

    public void finishLoadingADSource(string placementId, ATCallbackInfo callbackInfo)
    {
    }

    public void failToLoadADSource(string placementId, ATCallbackInfo callbackInfo, string code, string message)
    {
    }

    public void startBiddingADSource(string placementId, ATCallbackInfo callbackInfo)
    {
    }

    public void finishBiddingADSource(string placementId, ATCallbackInfo callbackInfo)
    {
    }

    public void failBiddingADSource(string placementId, ATCallbackInfo callbackInfo, string code, string message)
    {
    }

    public override void OnPlayRequestStarted()
    {
        if (UseAutoLoad())
        {
            EnsureAutoLoadRegistered();
            _client?.setAutoLocalExtra(Key, JsonMapper.ToJson(BuildInterstitialExtra()));
        }
    }

    public override int MaxLoadAttempts => ToponAdController.CurrentOptions?.InterstitialMaxLoadAttempts ?? base.MaxLoadAttempts;

    public override float LoadRetryDelaySeconds =>
        Math.Max(0f, (ToponAdController.CurrentOptions?.InterstitialLoadRetryDelayMs ?? 500) / 1000f);

    public override bool AutoPreloadOnInit => ToponAdController.CurrentOptions?.InterstitialPrewarmOnInit ?? true;

    private bool UseAutoLoad()
    {
        return ToponAdController.CurrentOptions?.InterstitialAutoLoad ?? true;
    }

    private void EnsureAutoLoadRegistered()
    {
        if (_autoLoadRegistered)
        {
            return;
        }

        _client?.addAutoLoadAdPlacementID(new[] { Key });
        _autoLoadRegistered = true;
    }

    private Dictionary<string, string> BuildInterstitialExtra()
    {
        return new Dictionary<string, string>
        {
            { ATConst.SCENARIO, AdScene ?? string.Empty }
        };
    }

    public override void EnterAdScenario(string scenario)
    {
        if (string.IsNullOrWhiteSpace(scenario) || string.Equals(scenario, "__default__", StringComparison.Ordinal))
        {
            return;
        }

        if (UseAutoLoad())
        {
            EnsureAutoLoadRegistered();
            _client?.entryAutoAdScenarioWithPlacementID(Key, scenario);
            return;
        }

        _client?.entryScenarioWithPlacementID(Key, scenario);
    }
}
