using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Advertisements;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class AdsManager : MonoBehaviour, IUnityAdsInitializationListener, IUnityAdsLoadListener, IUnityAdsShowListener
{
        // public string GAME_ID = "5486175"; //replace with your gameID from dashboard. note: will be different for each platform.

    // private const string BANNER_PLACEMENT = "banner";
    // private const string VIDEO_PLACEMENT = "video";
    // private const string REWARDED_VIDEO_PLACEMENT = "rewardedVideo";

    [SerializeField] private BannerPosition bannerPosition = BannerPosition.BOTTOM_CENTER;
    

    // private bool testMode = true;
    private bool showBanner = false;

    //utility wrappers for debuglog
    public delegate void DebugEvent(string msg);
    public static event DebugEvent OnDebugLog;

    // public GameObject missions_gameobject;


    //Game ID based on platform
    [SerializeField] string _androidGameId = "5486175";
    [SerializeField] string _iOSGameId = "5486174";

    // [SerializeField] string _androidGameId = "5491357";
    // [SerializeField] string _iOSGameId = "5491356";
    [SerializeField] bool _testMode = false; //Currently testing
    private string _gameId;

    [SerializeField] string _rewardedVideo_androidAdUnitId = "rewardedVideo";
    [SerializeField] string _rewardedVideo_iOsAdUnitId = "rewardedVideo";

    // [SerializeField] string _rewardedVideo_androidAdUnitId = "Rewarded_Android";
    // [SerializeField] string _rewardedVideo_iOsAdUnitId = "Rewarded_Android";
    string _adUnitId;

    // public TextMeshPro isSubscribedText;
    // public TextMeshProUGUI details;
    // public TextMeshProUGUI debug_msg;


    IEnumerator LoadAdCoroutine(){
        while (true){
            Advertisement.Load(_adUnitId, this);
            yield return new WaitForSeconds(2f); // Adjust wait time based on your needs
        }
    }


    MissionHandler mission_handler;
    MissionsManager missions_manager;
    public GameObject missionsManager_GO;
    public static string AdShowbutton;

    void OnEnable(){
        mission_handler = GetComponent<MissionHandler>();
        missions_manager = missionsManager_GO.GetComponent<MissionsManager>();
    }


    void Awake(){
        Initialize();
        StartCoroutine(LoadAdCoroutine()); //This code starts a coroutine that continuously calls LoadRewardedAd every 5 seconds (adjust as needed).
    }


    void Update(){

    }


    //Initialize method is responsible for initializing Unity Ads with a given GAME_ID
    public void Initialize()
    {
        //Check if Unity Ads is supported on the current platform
        // if (Advertisement.isSupported)
        // {
        //     DebugLog(Application.platform + " supported by Advertisement");
        // }

        //Set Game ID based on the platform, Android or iPhone
        #if UNITY_IOS
            _gameId = _iOSGameId;

        #elif UNITY_ANDROID
            _gameId = _androidGameId;

        #elif UNITY_EDITOR
            _gameId = _androidGameId; //Only for testing the functionality in the Editor

        #endif
            if (!Advertisement.isInitialized && Advertisement.isSupported)
            {
                Advertisement.Initialize(_gameId, _testMode, this);
            }

        // Get the Ad Unit ID for the current platform:
        _adUnitId = (Application.platform == RuntimePlatform.IPhonePlayer)
            ? _rewardedVideo_iOsAdUnitId
            : _rewardedVideo_androidAdUnitId;

        try{
            Advertisement.Initialize(_gameId, _testMode, this);
        }catch(Exception e){
            // debug_msg.text = "Initialize_Error: " + e.ToString();
        }
    }

    //Toggles between showing and hiding the banner ad
    public void ToggleBanner()
    {
        // showBanner = !showBanner;

        // if (showBanner)
        // {
        //     //Sets the banner position
        //     Advertisement.Banner.SetPosition(bannerPosition);
        //     Advertisement.Banner.Show(BANNER_PLACEMENT);
        // }
        // else
        // {
        //     Advertisement.Banner.Hide(false);
        // }
    }


    //Loads rewarded video ads
    public void LoadRewardedAd()
    {
        Advertisement.Load(_adUnitId, this);
    }

    //Show rewarded video ads
    public void ShowRewardedAd(){
        string buttonName = gameObject.name;
        AdShowbutton = buttonName;
        Debug.LogWarning("Clicked button name: " + buttonName);

        try{
            Advertisement.Show(_adUnitId, this);
        }catch(Exception e){
            // ads_not_ready_popup_text.text = "Show_Error: " + e.ToString();
        }
        
    }


    //Loads Interstitial (Non-Rewarded) Video Ads
    public void LoadNonRewardedAd()
    {
        Advertisement.Load(_adUnitId, this);
    }

    #region Interface Implementations
    public void OnInitializationComplete()
    {
        DebugLog("Init Success");
    }

    public void OnInitializationFailed(UnityAdsInitializationError error, string message)
    {
        // ads_not_ready_popup_text.text = "InitializationFailed: " + message;
        DebugLog($"Init Failed: [{error}]: {message}");
    }

    public void OnUnityAdsAdLoaded(string placementId)
    {
        // ShowRewardedAd();
        DebugLog($"Load Success: {placementId}");
    }

    public void OnUnityAdsFailedToLoad(string placementId, UnityAdsLoadError error, string message)
    {
        // ads_not_ready_popup_text.text = "LoadFailed: " + message;
        DebugLog($"Load Failed: [{error}:{placementId}] {message}");
    }

    public void OnUnityAdsShowFailure(string placementId, UnityAdsShowError error, string message)
    {
        // ads_not_ready_popup_text.text = "ShowFailed: " + message;
        DebugLog($"OnUnityAdsShowFailure: [{error}]: {message}");
    }

    public void OnUnityAdsShowStart(string placementId)
    {
        DebugLog($"OnUnityAdsShowStart: {placementId}");
    }

    public void OnUnityAdsShowClick(string placementId)
    {
        DebugLog($"OnUnityAdsShowClick: {placementId}");
    }

    //Called when the rewarded video ad has been shown to completion
    public void OnUnityAdsShowComplete(string placementId, UnityAdsShowCompletionState showCompletionState)
    {
        //Check if the Ad selected was a Rewarded video
        if (((placementId == _rewardedVideo_androidAdUnitId) || (placementId == _rewardedVideo_iOsAdUnitId)) && showCompletionState == UnityAdsShowCompletionState.COMPLETED)
        {
            //// Reward the user here
            // RewardUser();
            mission_handler.AdsWatched();
            Debug.LogWarning("Reward Given!");

            // missions_gameobject.SetActive(false);
            // missions_gameobject.SetActive(true);
            missions_manager.UpdateAdMissionUI(AdShowbutton);

        }

        DebugLog($"OnUnityAdsShowComplete: [{showCompletionState}]: {placementId}");
    }
    #endregion

    public void OnGameIDFieldChanged(string newInput)
    {
        _gameId = newInput;
    }

    public void ToggleTestMode(bool isOn)
    {
        _testMode = isOn;
    }

    //wrapper around debug.log to allow broadcasting log strings to the UI
    void DebugLog(string msg)
    {
        OnDebugLog?.Invoke(msg);
        Debug.Log(msg);
    }
}
