using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;
using System.Linq;
using UnityEngine.EventSystems;


public class MissionsManager : MonoBehaviour{
    public GameObject UI_parent;

    public GameObject[] contentPanels; //Mission Content, to be shown when tab is clicked
    public Button[] tabButtons; //Tab Content, Weekly or Monthly buttons

    public GameObject missionCanvas; // Reference to the Character_Selection canvas
    public GameObject missionPrefab; // Mission prefab

    public GameObject monthly_missionCanvas;
    public GameObject monthly_missionPrefab; // Mission prefab

    public GameObject no_missions;

    public Color missionComplete_Color = new Color(0.149f, 0.682f, 0.373f); // Color for "#26AE5F"
    public Color missionComplete_Color_bg = new Color(0.04f, 0.08627451f, 0.14509805f);   // #0A1626
    public Color normal_missionColor_bg = new Color(0.05882353f, 0.1647059f, 0.2980392f);   // #0A1626
    public Color normal_missionColor_text = new Color(1f, 1f, 1f);   // #0A1626

    // public Color missionComplete_Color_bg = new Color(0.03773585f, 0.08784413f, 0.1509434f); // Color for "#0C1827"

    int player_xp;
    PlayerData retrieved_playerData;

    public TMP_Text mission_type; //Weekly or Monthly

    private const string player_missionData = "Player_MissionData";

    [HideInInspector]
    public MissionProgress Player_missionProgress, retr;

    [HideInInspector]
    public List<MissionInfo> missionInfo, missionsInWeek; // List of character information

    [HideInInspector]
    public List<MissionInfo> retrieved_missionInfo; // List of character information

    [HideInInspector]
    public PlayerData playerData; // List of character information

    int current_mission;
    Completed_Missions_toAnimate completedMissionsToAnimate;

    public GameObject backButton;


    //Awake() is called as soon as the script is awakened (when the GameObject is created)
    private void Awake() {
        
    }


    private void OnEnable(){
        completedMissionsToAnimate = LoadPlayerData_CompletedMission_toAnimate();
        EventSystem.current.SetSelectedGameObject(backButton);

        //TABS in Missions UI
        ShowTab(0); //Start by showing Weekly Missions

        //Load Saved Completed Missions and then change their appearance in the Missions UI
        retr = LoadPlayer_MissionData();

        //For Weekly Missions
        foreach (int m in retr.completed_missions){
            String itm = "Mission_" + m.ToString();

            // Transform childTransform = animate_active.transform.Find("weekly_missions/Viewport/weeklyMissions_Content");
            // GameObject missionCanvas = childTransform.gameObject;

            // Debug.Log("Animate Mission " + m.ToString());

            // Call the function immediately for the first item
            try{
                // mission_completed(m, 0);
                changeCompletedMission_look(missionCanvas, m, itm);
            }catch(Exception e){
                Debug.Log("UI changed");
            }
        }

        string result3 = ListToString(retr.completed_missions);
        Debug.Log("Retrieved Completed Missions: " + result3);

       
    }



    // public void anim(){
    //     GameObject UI_ParentObject = GameObject.Find("UI");    //No issue finding this
    //     GameObject Mission_GameObject = UI_ParentObject.transform.Find("Missions").gameObject;

    //     GameObject animate_completed_mission_instance = Instantiate(Mission_GameObject, UI_ParentObject.transform);
    //     animate_completed_mission_instance.name = "Animate_Completed_Mission";
    //     Debug.Log("GRILL");
    // }


    // GameObject UI_ParentObject;
    // Start is called before the first frame update
    void Start(){

        // Attach button click events
        for (int i = 0; i < tabButtons.Length; i++){
            int tabIndex = i; // Capture the current value of i
            tabButtons[i].onClick.AddListener(() => ShowTab(tabIndex));
        }

        //Get Player Prefs and then XP
        PlayerData retrieved_playerData = LoadPlayerData();
        player_xp = retrieved_playerData.xp;
        
        if (PlayerPrefs.HasKey(player_missionData)){
            Debug.Log("Has Key");
            retr = LoadPlayer_MissionData();    //Works

        }else{ //no mission progress saved, start somewhere, save and load
            Debug.Log("No Key");

            Player_missionProgress = new MissionProgress { start_date = (DateTime.Now).ToString("MM/dd/yyyy hh:mm:ss"), current_week = 1, current_month = 1, 
                completed_missions = new List<int> { } };
            SavePlayer_MissionData(Player_missionProgress); //Saves the player's mission_progress data
            retr = LoadPlayer_MissionData();
        }


        //Get the WEEK the user is at in terms of progress
        int SavedPlayer_MissionWeek = retr.current_week; //Gets week
        Debug.Log("WeekX " + SavedPlayer_MissionWeek.ToString());

        // Missions in the game, more can be added as needed later on!
        missionInfo = new List<MissionInfo>
        {
            //A SEASON runs for 3 MONTHS, Each Week has 5 missions total
            //MONTH 1
            #region
                //WEEK 1, 400XP
                new MissionInfo { missionID = 1, missionTitle = "Survive the first 20 seconds of the game without taking a hit", missionDescription = "Survive for 20 seconds", missionXP = 100, missionProgressCount = 3, month = 1, week = 1},
                new MissionInfo { missionID = 2, missionTitle = "Punch opponent 5 times in a row", missionDescription = "5 consecutive punches", missionXP = 50, missionProgressCount = 3, month = 1, week = 1},
                new MissionInfo { missionID = 3, missionTitle = "Kick opponent 3 times in a row", missionDescription = "3 consecutive kicks", missionXP = 50, missionProgressCount = 3, month = 1, week = 1},
                new MissionInfo { missionID = 4, missionTitle = "Perform Kick-Punch-Kick combo", missionDescription = "KPK combo Hit", missionXP = 100, missionProgressCount = 3, month = 1, week = 1},
                new MissionInfo { missionID = 5, missionTitle = "Win 2 rounds in a row", missionDescription = "Win 2 consecutive rounds", missionXP = 100, missionProgressCount = 2, month = 1, week = 1},

                //WEEK 2, 400XP | Total 800XP
                new MissionInfo { missionID = 6, missionTitle = "Complete any 2 missions", missionDescription = "Complete 2 missions in this week", missionXP = 50, missionProgressCount = 2, month = 1, week = 2},
                new MissionInfo { missionID = 7, missionTitle = "Win 2 matches in a row", missionDescription = "Win 2 consecutive matches", missionXP = 100, missionProgressCount = 2, month = 1, week = 2},
                new MissionInfo { missionID = 8, missionTitle = "Win a round with health not less than 50%", missionDescription = "Win with health less than 50%", missionXP = 50, missionProgressCount = 3, month = 1, week = 2},
                new MissionInfo { missionID = 9, missionTitle = "Reach 500 XP", missionDescription = "Reach 200 XP", missionXP = 50, missionProgressCount = 3, month = 1, week = 2},
                new MissionInfo { missionID = 10, missionTitle = "Rank up to Level 2 Bronze", missionDescription = "Reach Level 2 Bronze", missionXP = 150, missionProgressCount = 3, month = 1, week = 2},

                //WEEK 3, 500XP | Total 1300XP
                new MissionInfo { missionID = 11, missionTitle = "Land a 5-hit punch combo", missionDescription = "Land 5 consecutive Punch hits", missionXP = 100, missionProgressCount = 3, month = 1, week = 3},
                new MissionInfo { missionID = 12, missionTitle = "Win a Perfect round", missionDescription = "Win a round without taking damage (Perfect round)", missionXP = 100, missionProgressCount = 3, month = 1, week = 3},
                new MissionInfo { missionID = 13, missionTitle = "Complete a match in under 30 seconds", missionDescription = "Complete a match under 30 seconds", missionXP = 200, missionProgressCount = 3, month = 1, week = 3},
                new MissionInfo { missionID = 14, missionTitle = "Complete 3 missions in a single match", missionDescription = "Complete 3 missions in a single match", missionXP = 50, missionProgressCount = 3, month = 1, week = 3},
                new MissionInfo { missionID = 15, missionTitle = "Win a round using only punches", missionDescription = "Win a round with punches", missionXP = 50, missionProgressCount = 3, month = 1, week = 3},
                
                //WEEK 4, 500XP | Total 1800XP
                new MissionInfo { missionID = 16, missionTitle = "Win with 10% health remaining", missionDescription = "Win a round with less than 10% health remaining", missionXP = 50, missionProgressCount = 3, month = 1, week = 4},
                new MissionInfo { missionID = 17, missionTitle = "Achieve a win streak of 5 matches in a row", missionDescription = "Win 2 consecutive versus battles", missionXP = 200, missionProgressCount = 3, month = 1, week = 4},
                new MissionInfo { missionID = 18, missionTitle = "Watch 2 Ads", missionDescription = "Watch 2 Ads", missionXP = 50, missionProgressCount = 2, month = 1, week = 4},
                new MissionInfo { missionID = 19, missionTitle = "Reach 1600 XP", missionDescription = "Reach 1500 XP", missionXP = 50, missionProgressCount = 3, month = 1, week = 4},
                new MissionInfo { missionID = 20, missionTitle = "Rank up to Level 2 Silver", missionDescription = "Rank up to Level 2 Silver", missionXP = 150, missionProgressCount = 3, month = 1, week = 4},
            #endregion


            //MONTH 2
            #region
                //WEEEK 1, 500XP | Total 2300XP
                new MissionInfo { missionID = 21, missionTitle = "Win a match without walking around", missionDescription = "Win a match without walking around", missionXP = 100, missionProgressCount = 3, month = 2, week = 1},
                new MissionInfo { missionID = 22, missionTitle = "Watch 10 Ads", missionDescription = "Watch 10 Ads", missionXP = 50, missionProgressCount = 10, month = 2, week = 1},
                new MissionInfo { missionID = 23, missionTitle = "Achieve a perfect round using only kicks", missionDescription = "Achieve a perfect round using only kicks", missionXP = 100, missionProgressCount = 3, month = 2, week = 1},
                new MissionInfo { missionID = 24, missionTitle = "Win a round sustaining less than 5 hits from opponent", missionDescription = "Win a round sustaining less than 5 hits from opponent", missionXP = 150, missionProgressCount = 3, month = 2, week = 1},
                new MissionInfo { missionID = 25, missionTitle = "Win a match using only punches", missionDescription = "Win a match using only punches", missionXP = 100, missionProgressCount = 3, month = 2, week = 1},

                //WEEK 2, 400XP | Total 2700XP
                new MissionInfo { missionID = 26, missionTitle = "Win a match with not less than 60% health in the final round", missionDescription = "Win a match with not less than 60% health in the final round", missionXP = 50, missionProgressCount = 3, month = 2, week = 2},
                new MissionInfo { missionID = 27, missionTitle = "Perform Punch-Kick-Kick combo", missionDescription = "Perform Punch-Kick-Kick combo", missionXP = 100, missionProgressCount = 3, month = 2, week = 2},
                new MissionInfo { missionID = 28, missionTitle = "Reach 2400 XP", missionDescription = "Reach 2400 XP", missionXP = 50, missionProgressCount = 3, month = 2, week = 2},
                new MissionInfo { missionID = 29, missionTitle = "Rank up to Level 2 Gold", missionDescription = "Rank up to Level 2 Gold", missionXP = 150, missionProgressCount = 3, month = 2, week = 2},
                new MissionInfo { missionID = 30, missionTitle = "Complete this week’s missions", missionDescription = "Complete this week’s missions", missionXP = 50, missionProgressCount = 3, month = 2, week = 2},

                //WEEK 3, 300XP | Total 3000XP
                new MissionInfo { missionID = 31, missionTitle = "Complete a round in under 30 seconds", missionDescription = "Complete a round in under 30 seconds", missionXP = 50, missionProgressCount = 3, month = 2, week = 3},
                new MissionInfo { missionID = 32, missionTitle = "Watch 5 Ads", missionDescription = "Win a match using a character you've never played before", missionXP = 50, missionProgressCount = 5, month = 2, week = 3},
                new MissionInfo { missionID = 33, missionTitle = "Achieve a win with less than 5% health remaining in each round", missionDescription = "Achieve a win with less than 5% health remaining in each round", missionXP = 100, missionProgressCount = 3, month = 2, week = 3},
                new MissionInfo { missionID = 34, missionTitle = "Win a round with more 75% health remaining", missionDescription = "Win a round with more 75% health remaining", missionXP = 50, missionProgressCount = 3, month = 2, week = 3},
                new MissionInfo { missionID = 35, missionTitle = "Complete this week’s missions", missionDescription = "Complete this week’s missions", missionXP = 50, missionProgressCount = 3, month = 2, week = 3},
                
                //WEEK 4, 900XP | Total 3900XP
                new MissionInfo { missionID = 36, missionTitle = "Play different matches for a total of 30 minutes", missionDescription = "Play different matches for a total of 30 minutes", missionXP = 500, missionProgressCount = 3, month = 2, week = 4},
                new MissionInfo { missionID = 37, missionTitle = "Watch 15 Ads", missionDescription = "Watch 15 Ads", missionXP = 50, missionProgressCount = 15, month = 2, week = 4},
                new MissionInfo { missionID = 38, missionTitle = "Perform Punch-Punch-Kick attack", missionDescription = "Perform Punch-Punch-Kick attack", missionXP = 100, missionProgressCount = 3, month = 2, week = 4},
                new MissionInfo { missionID = 39, missionTitle = "Reach 3600 XP", missionDescription = "Reach 3600 XP", missionXP = 50, missionProgressCount = 3, month = 2, week = 4},
                new MissionInfo { missionID = 40, missionTitle = "Rank up to Level 1 Platinum", missionDescription = "Rank up to Level 1 Platinum", missionXP = 200, missionProgressCount = 3, month = 2, week = 4},
            #endregion


            //MONTH 3
            #region
                //WEEK 1, 500XP | Total 4400XP
                new MissionInfo { missionID = 41, missionTitle = "Perform a combo that does at least 30% damage", missionDescription = "Perform a combo that does at least 30% damage", missionXP = 100, missionProgressCount = 3, month = 3, week = 1},
                new MissionInfo { missionID = 42, missionTitle = "Win a round with a health difference of less than 10% between you and your opponent", missionDescription = "Win a round with a health difference of less than 10% between you and your opponent", missionXP = 150, missionProgressCount = 3, month = 3, week = 1},
                new MissionInfo { missionID = 43, missionTitle = "Reach 4200 XP", missionDescription = "Reach 4200 XP", missionXP = 50, missionProgressCount = 3, month = 3, week = 1},
                new MissionInfo { missionID = 44, missionTitle = "Rank up to Level 3 Platinum", missionDescription = "Rank up to Level 3 Platinum", missionXP = 150, missionProgressCount = 3, month = 3, week = 1},
                new MissionInfo { missionID = 45, missionTitle = "Complete this week's missions", missionDescription = "Complete this week's missions", missionXP = 50, missionProgressCount = 3, month = 3, week = 1},

                //WEEK 2, 600XP | Total 5000XP
                new MissionInfo { missionID = 46, missionTitle = "Achieve a win streak of 7 matches in a row", missionDescription = "Achieve a win streak of 7 matches in a row", missionXP = 200, missionProgressCount = 3, month = 3, week = 2},
                new MissionInfo { missionID = 47, missionTitle = "Win each round your character's health below 25%", missionDescription = "Win each round your character's health below 25%", missionXP = 150, missionProgressCount = 3, month = 3, week = 2},
                new MissionInfo { missionID = 48, missionTitle = "Reach 4800 XP", missionDescription = "Reach 4800 XP", missionXP = 50, missionProgressCount = 3, month = 3, week = 2},
                new MissionInfo { missionID = 49, missionTitle = "Rank up to Level 2 Diamond", missionDescription = "Rank up to Level 2 Diamond", missionXP = 250, missionProgressCount = 3, month = 3, week = 2},
                new MissionInfo { missionID = 50, missionTitle = "Complete this week's missions", missionDescription = "Complete this week's missions", missionXP = 50, missionProgressCount = 3, month = 3, week = 2},

                //WEEK 3, 500XP | Total 5500XP
                new MissionInfo { missionID = 51, missionTitle = "Complete all 3 rounds in under 3 minutes", missionDescription = "Complete all 3 rounds in under 3 minutes", missionXP = 150, missionProgressCount = 3, month = 3, week = 3},
                new MissionInfo { missionID = 52, missionTitle = "Watch 20 Ads", missionDescription = "Watch 20 Ads", missionXP = 100, missionProgressCount = 20, month = 3, week = 3},
                new MissionInfo { missionID = 53, missionTitle = "Reach 1000 XP", missionDescription = "Reach 1000 XP", missionXP = 50, missionProgressCount = 3, month = 3, week = 3},
                new MissionInfo { missionID = 54, missionTitle = "Rank up to Master Level", missionDescription = "Rank up to Master Level", missionXP = 150, missionProgressCount = 3, month = 3, week = 3},
                new MissionInfo { missionID = 55, missionTitle = "Complete this week's missions", missionDescription = "Complete this week's missions", missionXP = 50, missionProgressCount = 3, month = 3, week = 3},
                
                //WEEK 4, 500XP | Total 6000XP
                new MissionInfo { missionID = 56, missionTitle = "Complete 2 rounds in under 1 minute", missionDescription = "Complete 2 rounds in under 1 minute", missionXP = 100, missionProgressCount = 3, month = 3, week = 4},
                new MissionInfo { missionID = 57, missionTitle = "Defeat opponent using only Kick-Punch move", missionDescription = "Defeat opponent using only Kick-Punch move", missionXP = 100, missionProgressCount = 3, month = 3, week = 4},
                new MissionInfo { missionID = 58, missionTitle = "Reach 1200 XP", missionDescription = "Reach 1200 XP", missionXP = 50, missionProgressCount = 3, month = 3, week = 4},
                new MissionInfo { missionID = 59, missionTitle = "Rank up to Apex Predator Level", missionDescription = "Rank up to Apex Predator Level", missionXP = 200, missionProgressCount = 3, month = 3, week = 4},
                new MissionInfo { missionID = 60, missionTitle = "Complete this week's missions", missionDescription = "Complete this week's missions", missionXP = 50, missionProgressCount = 3, month = 3, week = 4},
            #endregion

        };


        // int current_week = get_CurrentWeek();
        int current_week = retr.current_week;
        Debug.Log("Here : " + current_week.ToString());

        int current_month = retr.current_month;

        //Get Missions in the week
        // missionsInWeek = missionInfo.Where(mission => mission.week == current_week).ToList();    //starts at week 1 if no progress info present

        missionsInWeek = missionInfo.Where(mission => ((mission.month == current_month) && (mission.week == current_week))).ToList();    //starts at week 1 if no progress info present

        //Populate the UI with the missions above
        PopulateShopWithMissions(); //Weekly Missions
        
        Debug.Log($"We are Back {completedMissionsToAnimate.animation_status}");

        Completed_Missions_toAnimate completedMissionsToAnimate1 = LoadPlayerData_CompletedMission_toAnimate();
        Debug.Log($"Last Attempt {completedMissionsToAnimate1.animation_status}");

        if (completedMissionsToAnimate1.animation_status == 0){

            //Sort Completed Animations Here
            var sortedCompletedMissions = (completedMissionsToAnimate.completed_missions_toAnimate_data).OrderBy(x => x).ToList();
            completedMissionsToAnimate.completed_missions_toAnimate_data = sortedCompletedMissions;
            SaveCompleted_Missions_toAnimate(completedMissionsToAnimate);

            CreateInstanceOfMissions_forAnimation();
        }

        //Delete this now
        Completed_Missions_toAnimate tl = LoadPlayerData_CompletedMission_toAnimate();
        string result1 = ListToString(tl.completed_missions_toAnimate_data);
        Debug.Log("Mission Animate: " + result1);
        //Delete this now

    }

    // LoadPlayer_MissionData
    MissionProgress retrieved_missionProgress;
    public int get_CurrentWeek(){
        //From the recorded original date, get the current date, then based on the time elapsed in between, display missions based on the week
        retrieved_missionProgress = LoadPlayer_MissionData();

        // Parse the string back to DateTime
        DateTime parsed_OriginalDate = DateTime.Parse(retrieved_missionProgress.start_date);

        // DateTime date_now = DateTime.Parse("02/29/2024 15:51:26");
        DateTime date_now = DateTime.Now;
        // Debug.Log(date_now);

        // Calculate the time span between the two dates
        TimeSpan timeDifference = date_now - parsed_OriginalDate;

        // Calculate the number of weeks
        int weeksElapsed = ((int)(timeDifference.TotalDays / 7)) + 1;
        retrieved_missionProgress.current_week = weeksElapsed;
        SavePlayer_MissionData(retrieved_missionProgress);

        // Debug.Log("Weeks Elapsed: " + weeksElapsed);

        return weeksElapsed;

        // Print the result
        // Debug.Log("Weeks Elapsed: " + weeksElapsed);
    }


    GameObject Mission_GameObject;
    public void CreateInstanceOfMissions_forAnimation(){
        //Create an instance of Missions then Animate
        GameObject UI_ParentObject = GameObject.Find("UI");    //No issue finding this
        Mission_GameObject = UI_ParentObject.transform.Find("Missions").gameObject;

        GameObject animate_completed_mission_instance = Instantiate(Mission_GameObject, UI_ParentObject.transform);
        animate_completed_mission_instance.name = "Animate_Completed_Mission";

        GameObject animate_content = animate_completed_mission_instance.transform.Find("mission_content/weekly_missions/Viewport/weeklyMissions_Content").gameObject;
        GameObject monthlyanimate_content = animate_completed_mission_instance.transform.Find("mission_content/monthly_missions/Viewport/MonthlyMissions_Content").gameObject;

        // completedMissionsToAnimate = LoadPlayerData_CompletedMission_toAnimate();
        // completedMissionsToAnimate.completed_missions_toAnimate_data


        //For Weekly, REMOVE marked completed missions
        foreach (int mission_x in completedMissionsToAnimate.completed_missions_toAnimate_data){
            String itm = "Mission_" + mission_x.ToString();
            RemoveCompletedMission_look(animate_content, mission_x, itm);
        }

        //Remove the Mission Tabs, and Back button, for the Completed Missions Animation after a Match is over
        GameObject mission_tabs = animate_completed_mission_instance.transform.Find("mission_Tabs").gameObject;
        GameObject mission_backButtons = animate_completed_mission_instance.transform.Find("Back_button").gameObject;
        GameObject mission_script = animate_completed_mission_instance.transform.Find("Mission_Script").gameObject;
        Destroy(mission_tabs);
        Destroy(mission_backButtons);
        Destroy(mission_script);


        StartCoroutine(AnimateMissionsSequentially(animate_completed_mission_instance, animate_content, monthlyanimate_content));
    }



    //Populate the UI with Weekly and Monthly Missions
    #region
    public static List<int> weeklyMissions_Ads;
    GameObject adDetails;

    //Displays Weekly missions on the Missions UI canvas
    void PopulateShopWithMissions(){
        weeklyMissions_Ads = new List<int>(){ 18, 22, 32, 37, 52 }; //List of all missions that are related to Watching Ads

        //If there are no more missions
        if (missionsInWeek.Count == 0){
            // no_missions.SetActive(true);
        }

        retr = LoadPlayer_MissionData();

        // Loop through the character list and create icons for each character
        foreach (MissionInfo mission_info in missionsInWeek){
            // Instantiate the mission prefab
            GameObject mission_item = Instantiate(missionPrefab, missionCanvas.transform);
            mission_item.name = "Mission_" + mission_info.missionID;
            String itm = "Mission_" + (mission_info.missionID).ToString();

            // Access the mission title
            TextMeshProUGUI missionprefab_title = mission_item.transform.Find("mission_title").GetComponent<TextMeshProUGUI>();
            missionprefab_title.text = mission_info.missionTitle;

            TextMeshProUGUI missionprefab_details = mission_item.transform.Find("mission_details").GetComponent<TextMeshProUGUI>();
            missionprefab_details.text = mission_info.missionDescription;

            // Access the mission xp
            TextMeshProUGUI missionprefab_xp = mission_item.transform.Find("mission_xp").GetComponent<TextMeshProUGUI>();
            missionprefab_xp.text = (mission_info.missionXP).ToString();

            // Access the mission xp
            TextMeshProUGUI missionprefab_desc = mission_item.transform.Find("mission_details").GetComponent<TextMeshProUGUI>();
            missionprefab_desc.text = mission_info.missionDescription;


            //If it is an Ad Mission
            if (weeklyMissions_Ads.Contains(mission_info.missionID)){
                Debug.LogWarning("Cont " + (mission_info.missionID).ToString());

                //Show Watch Ads Buttons
                adDetails = mission_item.transform.Find("AdMission").gameObject;
                adDetails.SetActive(true);

                GameObject adViewBtn = adDetails.transform.Find("WatchAd").gameObject;
                adViewBtn.name = (mission_info.missionID).ToString();

                string AdsSearchTerm = "Mission" + (mission_info.missionID).ToString();
                // Debug.LogWarning("AdsSearchTerm = " + AdsSearchTerm);

                string result3dx = ListToString(retr.completed_missions_inprogress);

                string AdMissionSearch = retr.completed_missions_inprogress.FirstOrDefault(s => s.StartsWith(AdsSearchTerm));

                //If not yet present
                if (AdMissionSearch == null){
                    string to_add = string.Format("Mission{0}: 0", mission_info.missionID);
                    retr.completed_missions_inprogress.Add(to_add);
                    SavePlayer_MissionData(retr);
                }
                AdMissionSearch = retr.completed_missions_inprogress.FirstOrDefault(s => s.StartsWith(AdsSearchTerm));
                Debug.LogWarning("AdMissionSearch: " + AdMissionSearch);

                string AdMissionValue = getMissionValue(AdMissionSearch);
                int AdsWatchedCount = int.Parse(AdMissionValue);    //Get number of watched ads

                TextMeshProUGUI missionAdStatus = mission_item.transform.Find("AdMission/AdMission_status").GetComponent<TextMeshProUGUI>();
                missionAdStatus.text = string.Format("({0}/{1} Watched)", AdsWatchedCount, mission_info.missionProgressCount);
                Debug.LogWarning("Ads = " + AdsWatchedCount.ToString());
            }

            //If a mission is completed, change text color to Green to indicate that it has been completed
            if (retr.completed_missions.Contains(mission_info.missionID)){
                changeCompletedMission_look(missionCanvas, mission_info.missionID, itm);

                //If Ads Missions is completed
                if (weeklyMissions_Ads.Contains(mission_info.missionID)){
                    adDetails.SetActive(false);
                }
            }
        }

        // Disable the original prefab
        missionPrefab.SetActive(false);
    }

    #endregion

   

    public string getMissionValue(string Search_Result){
        string[] parts = Search_Result.Split(':');
        string missionID_StoredFound = parts[1].Trim();    //Get the value (num value), Trim() removes removes whitespaces if any, then Parses to int value

        Debug.LogWarning("missionID_StoredFound = " + missionID_StoredFound);
        return missionID_StoredFound;
    }



    //Changes the appearance of a completed mission on the UI, updating their look
    public void changeCompletedMission_look(GameObject missionCanv, int mission_number, String completedMission_UI_reference){
        GameObject completedMission = missionCanv.transform.Find(completedMission_UI_reference)?.gameObject;
        if (completedMission != null){
            // Change background color
            Image missionImage  = completedMission.transform.Find("Image").GetComponent<Image>();
            missionImage.color = missionComplete_Color_bg;

            // Access the mission title
            TextMeshProUGUI missionprefab_title = completedMission.transform.Find("mission_title").GetComponent<TextMeshProUGUI>();
            missionprefab_title.color = missionComplete_Color;

            TextMeshProUGUI missionprefab_details = completedMission.transform.Find("mission_details").GetComponent<TextMeshProUGUI>();
            missionprefab_details.color = missionComplete_Color;

            // Access the mission xp
            TextMeshProUGUI missionprefab_xp = completedMission.transform.Find("mission_xp").GetComponent<TextMeshProUGUI>();
            missionprefab_xp.color = missionComplete_Color;

            TextMeshProUGUI missionprefab_xp_text = completedMission.transform.Find("XP").GetComponent<TextMeshProUGUI>();
            missionprefab_xp_text.color = missionComplete_Color;

            // Access the mission xp
            TextMeshProUGUI missionprefab_desc = completedMission.transform.Find("mission_details").GetComponent<TextMeshProUGUI>();
            missionprefab_desc.color = missionComplete_Color;

            // Access Slider
            GameObject completedMission_slider = completedMission.transform.Find("mission_slider")?.gameObject;
            Image completedMission_slider_img = completedMission_slider.transform.Find("Background").GetComponent<Image>();
            completedMission_slider_img.color = missionComplete_Color;
        }
    }


    public void RemoveCompletedMission_look(GameObject missionCanv, int mission_number, String completedMission_UI_reference){
        GameObject completedMission = missionCanv.transform.Find(completedMission_UI_reference)?.gameObject;
        if (completedMission != null){

            // Change background color
            Image missionImage  = completedMission.transform.Find("Image").GetComponent<Image>();
            // missionImage.color = normal_missionColor_bg;

            // Access the mission title
            TextMeshProUGUI missionprefab_title = completedMission.transform.Find("mission_title").GetComponent<TextMeshProUGUI>();
            missionprefab_title.color = normal_missionColor_text;

            TextMeshProUGUI missionprefab_details = completedMission.transform.Find("mission_details").GetComponent<TextMeshProUGUI>();
            missionprefab_details.color = normal_missionColor_text;

            // Access the mission xp
            TextMeshProUGUI missionprefab_xp = completedMission.transform.Find("mission_xp").GetComponent<TextMeshProUGUI>();
            missionprefab_xp.color = normal_missionColor_text;

            TextMeshProUGUI missionprefab_xp_text = completedMission.transform.Find("XP").GetComponent<TextMeshProUGUI>();
            missionprefab_xp_text.color = normal_missionColor_text;

            // Access the mission xp
            TextMeshProUGUI missionprefab_desc = completedMission.transform.Find("mission_details").GetComponent<TextMeshProUGUI>();
            missionprefab_desc.color = normal_missionColor_text;

            // Access Slider
            GameObject completedMission_slider = completedMission.transform.Find("mission_slider")?.gameObject;
            Image completedMission_slider_img = completedMission_slider.transform.Find("Background").GetComponent<Image>();
            completedMission_slider_img.color = normal_missionColor_text;
        }else{
            Debug.Log("We are here");
        }
    }


    public void start_from_another_script(){
        // ClearMissionUI();
        Start();
    }


    //Increments the current mission, adds it to the completed list, and saves the progress.
    //Just for mission completion simulation purpose
    // int current_mission = missionsInWeek[0].missionID;
    // public void mission_completed(int missionID_completed, String UI_reference_update){


    //NOTE: This should not be linked with xp, ????
    public void mission_completed(int missionID_completed, int UI_reference_update){
        retr = LoadPlayer_MissionData();
        current_mission = missionID_completed;

        //Get the exact mission being referred to
        // missionsInWeek = missionInfo.Where(mission => mission.week == retr.current_week).ToList();

        //Get the exact mission being referred to
        MissionInfo mission1 = missionsInWeek.Find(m => m.missionID == current_mission);    //is null

        PlayerData retrieved_playerData = LoadPlayerData();
        retrieved_playerData.xp = retrieved_playerData.xp + mission1.missionXP;

        // retrieved_playerData = LoadPlayerData();
        Debug.Log("XP = " + (retrieved_playerData.xp).ToString());

        // player_xp = player_xp + mission1.missionXP; //There is an issue here
        // retrieved_playerData.xp = player_xp;

        // string jsonData = JsonUtility.ToJson(retrieved_playerData);

        // PlayerPrefs.SetString("Player_RewardsData", jsonData); // Details stored as "PlayerData"
        // PlayerPrefs.Save();

        SavePlayerData(retrieved_playerData);

        // retrieved_playerData = LoadPlayerData();
        // Debug.Log("XP = " + retrieved_playerData.xp);

    }


    // Helper method to clear existing mission UI elements
    void ClearMissionUI(GameObject Canvas_toClear){  
        foreach (Transform child in Canvas_toClear.transform){
            if ((child.name != "mission_prefab") && (child.name != "no_missions")){
                Destroy(child.gameObject);
            }
        }
    }


    //Delete this
    string ListToString<T>(List<T> list){
        // Use string.Join to concatenate the elements of the list into a string
        return string.Join(", ", list);
    }



    public void UpdateAdMissionUI(string AdShowbutton){
        //18 is a parameter
        Debug.LogWarning("UpdateAdMissionUI");

        retr = LoadPlayer_MissionData();

        // string AdsSearchTerm = "Mission" + (mission_info.missionID).ToString();
        string AdsSearchTerm = "Mission" + AdShowbutton;
        string AdMissionSearch = retr.completed_missions_inprogress.FirstOrDefault(s => s.StartsWith(AdsSearchTerm));
        string AdMissionValue = getMissionValue(AdMissionSearch);
        int AdsWatchedCount = int.Parse(AdMissionValue);

        Missions missions = GetComponent<Missions>();
        int mission_ProgressCount = missions.getMissionProgressCount(int.Parse(AdShowbutton));

        // string missionInstance_str = string.Format("Mission_18", mID);
        string missionInstance_str = string.Format("Mission_{0}", int.Parse(AdShowbutton));
        GameObject missionInstance = missionCanvas.transform.Find(missionInstance_str).gameObject;
        TextMeshProUGUI mission_text = missionInstance.transform.Find("AdMission/AdMission_status").GetComponent<TextMeshProUGUI>();
        mission_text.text = string.Format("({0}/{1} Watched)", AdsWatchedCount, mission_ProgressCount);


        if (AdsWatchedCount == mission_ProgressCount){  //Ad missions completed
            changeCompletedMission_look(missionCanvas, int.Parse(AdShowbutton), missionInstance_str);
            GameObject adViewBtn = adDetails.transform.Find(AdShowbutton).gameObject;
            adViewBtn.SetActive(false);
        }

        // TextMeshProUGUI missionAdStatus = mission_item.transform.Find("AdMission/AdMission_status").GetComponent<TextMeshProUGUI>();


        // AdMissionSearch = retr.completed_missions_inprogress.FirstOrDefault(s => s.StartsWith(AdsSearchTerm));
        // string AdMissionValue = getMissionValue(AdMissionSearch);
        // int AdsWatchedCount = int.Parse(AdMissionValue);
    }


    //Function to display or hide tabs, Weekly or Monthly Missions
    private void ShowTab(int tabIndex){
        // Hide all content panels
        foreach (var panel in contentPanels){
            panel.SetActive(false);
        }

        // Show the selected content panel
        contentPanels[tabIndex].SetActive(true);

        if (tabIndex == 0){
            mission_type.text = "WEEKLY MISSIONS";
        }else{
            mission_type.text = "MONTHLY MISSIONS";
        }
    }


    List<int> completed_missions_toAnimate, Monthly_completed_missions_toAnimate;

    [HideInInspector]
    public Completed_Missions_toAnimate retrieved_completed_missions_toAnimate;

    GameObject mission_UI;
    public void AnimateCompletedMissions(){
        // gameObject.SetActive(false);
        retrieved_completed_missions_toAnimate = LoadPlayerData_CompletedMission_toAnimate();

        completed_missions_toAnimate = retrieved_completed_missions_toAnimate.completed_missions_toAnimate_data;

        //Find "Animate_Completed_Mission" GameObject
        GameObject missionManager_GameObject = UI_parent.transform.Find("Missions/Mission_Script").gameObject;
        MissionsManager missionManager = missionManager_GameObject.GetComponent<MissionsManager>();

        //Deactivate current GameObject
        mission_UI = UI_parent.transform.Find("Missions").gameObject;
        mission_UI.SetActive(true);

        Debug.Log("GRILL");

        GameObject animate_active = UI_parent.transform.Find("Animate_Completed_Mission").gameObject;
        animate_active.SetActive(true);

        //Animate here
        StartCoroutine(AnimateMissionsSequentially(missionManager, animate_active));

        // animate_active.SetActive(false);
    }



    //Params are (Animation Instance, Weekly Missions, Monthly Missions) 
    IEnumerator AnimateMissionsSequentially(GameObject animate_completed_mission_instance, GameObject animate_content, GameObject monthlyanimate_content){

        GameObject weeklyanimate_content_parent = animate_completed_mission_instance.transform.Find("mission_content/weekly_missions").gameObject;
        weeklyanimate_content_parent.SetActive(true);

        // GameObject monthlyanimate_content_parent = animate_completed_mission_instance.transform.Find("mission_content/monthly_missions").gameObject;
        //Add Button to move on
        GameObject continueToRewards = (animate_completed_mission_instance.transform.Find("Continue").gameObject);
        continueToRewards.SetActive(true);
        Button BtnContinueToRewards = continueToRewards.GetComponent<Button>();

        BtnContinueToRewards.onClick.AddListener(() => destroyAnimateMissionsInstance(animate_completed_mission_instance));
        //select it by default to enable navingation in pc version
        BtnContinueToRewards.Select();

        //Remove back button
        GameObject backBtnInMissions = (animate_completed_mission_instance.transform.Find("BackButton").gameObject);
        backBtnInMissions.SetActive(false);


        yield return new WaitForSeconds(0.6f); //Initial Delay

        //Animate Completed Weekly Missions
        foreach (int m in completedMissionsToAnimate.completed_missions_toAnimate_data){
            String itm = "Mission_" + m.ToString();
            changeCompletedMission_look(animate_content, m, itm);

            // Wait for 5 seconds before the next iteration
            yield return new WaitForSeconds(0.6f);
        }

        // weeklyanimate_content_parent.SetActive(false);

        completedMissionsToAnimate = LoadPlayerData_CompletedMission_toAnimate();
        completedMissionsToAnimate.animation_status = 1;
        completedMissionsToAnimate.completed_missions_toAnimate_data = new List<int> { };
        SaveCompleted_Missions_toAnimate(completedMissionsToAnimate);
       
    }


    // Function to destory the Instance created to show Completed Missions
    void destroyAnimateMissionsInstance(GameObject animate_completed_mission_instance){

        Destroy(animate_completed_mission_instance);
        GameObject rewards_UI = UI_parent.transform.Find("Rewards").gameObject;
        rewards_UI.SetActive(true);     //Enable Rewards UI

        GameObject RewardsPopUp_GameObject = rewards_UI.transform.Find("RewardsPopUp").gameObject;
        RewardsPopUp_GameObject.SetActive(false);

        PlayerData retrieved_playerData = LoadPlayerData();
        // Debug.Log($"R = {retrieved_playerData.rank}, PR = {retrieved_playerData.prevRank} ");

        RankIconManager rim = GetComponent<RankIconManager>();


        //If Rank or Rank Level are different, then show popup showing the Ranking up
        if ((retrieved_playerData.rank != retrieved_playerData.prevRank) || (retrieved_playerData.prevrank_level != retrieved_playerData.rank_level)){
            Debug.Log("There has been change in the Rank");
            RewardsPopUp_GameObject.SetActive(true);

            //Get the Sprite for the Rank
            Sprite rankSprite = rim.rankSprite(retrieved_playerData.rank, retrieved_playerData.rank_level);
            Image RewardsPopUp_RankIcon = (RewardsPopUp_GameObject.transform.Find("RankIcon/Image").gameObject).GetComponent<Image>();
            TextMeshProUGUI RewardsPopUp_RankLevelText = (RewardsPopUp_GameObject.transform.Find("RankLevel").gameObject).GetComponent<TextMeshProUGUI>();
            RewardsPopUp_RankIcon.sprite = rankSprite;
            RewardsPopUp_RankLevelText.text = $"Level {retrieved_playerData.rank_level}";

            //onclick button
            Button rewardsPopUp_Btn = rewards_UI.transform.Find("RewardsPopUp/BG_Button").GetComponent<Button>();
            rewardsPopUp_Btn.onClick.AddListener(() => GoToHome(rewards_UI));
            rewardsPopUp_Btn.Select();

        }else{
            Debug.Log("Same Rewards");
            RewardsPopUp_GameObject.SetActive(false);

            Button continueBtn = rewards_UI.transform.Find("Rewards_text/rewardsContinue").GetComponent<Button>();
            continueBtn.onClick.AddListener(() => GoToHome (rewards_UI));
            continueBtn.Select();
        }
    }



    #region
    //Attach a function here, when button is clicked to proceed
    //Launch Loading Screen
        void GoToHome(GameObject rewards_UI){
            rewards_UI.SetActive(false);
            GameObject missions_UI = UI_parent.transform.Find("Missions").gameObject;
            missions_UI.SetActive(false);     //Enable Rewards UI
            GameObject home_UI = UI_parent.transform.Find("Home").gameObject;
            home_UI.SetActive(true);     //Enable Rewards UI
            Debug.Log("Going Home!");
        
        }
    #endregion



    GameObject monthly_mission_show;
    IEnumerator AnimateMissionsSequentially(MissionsManager missionManager, GameObject animate_active){
        Debug.Log("Started");

        //Gets the instantiated UI for the animation
        GameObject normal_mission_show = animate_active.transform.Find("mission_content/weekly_missions").gameObject;
        // GameObject normal_mission_show = normal_missionTransform.gameObject;


        //Used for the animation
        GameObject missionCanvas = animate_active.transform.Find("mission_content/weekly_missions/Viewport/weeklyMissions_Content").gameObject;
        // GameObject missionCanvas = childTransform.gameObject;


        yield return new WaitForSeconds(0.6f); //Initial Delay

        //Animate Completed Weekly Missions
        foreach (int m in completed_missions_toAnimate){
            String itm = "Mission_" + m.ToString();
            changeCompletedMission_look(missionCanvas, m, itm);

            // Wait for 5 seconds before the next iteration
            yield return new WaitForSeconds(0.6f);
        }

        normal_mission_show.SetActive(false);
        // missionCanvas.SetActive(false);

        //All animations done
        Destroy(animate_active);


        GameObject rewards_UI = UI_parent.transform.Find("Rewards").gameObject;
        rewards_UI.SetActive(true);
        
    }




    //**** PLAYER PREFS    

    //Load Completed Missions that need to be Animated after a match is complete
    private const string player_completed_Missions_toAnimate = "Player_Completed_Missions_toAnimate";
    Completed_Missions_toAnimate LoadPlayerData_CompletedMission_toAnimate(){
        string jsonData2 = PlayerPrefs.GetString(player_completed_Missions_toAnimate, "{}"); // Details were stored as "PlayerData"
        return JsonUtility.FromJson<Completed_Missions_toAnimate>(jsonData2);
    }

    private void SaveCompleted_Missions_toAnimate(Completed_Missions_toAnimate data){
        string jsonData = JsonUtility.ToJson(data);
        // PlayerPrefs.SetString("Player_MissionData", jsonData); // Details stored as "PlayerData"
        PlayerPrefs.SetString(player_completed_Missions_toAnimate, jsonData); // Details stored as "PlayerData"
        PlayerPrefs.Save();
    }


    //Serializes and Saves mission progress to PlayerPrefs.
    private void SavePlayer_MissionData(MissionProgress data){
        string jsonData = JsonUtility.ToJson(data);
        // PlayerPrefs.SetString("Player_MissionData", jsonData); // Details stored as "PlayerData"
        PlayerPrefs.SetString(player_missionData, jsonData); // Details stored as "PlayerData"
        PlayerPrefs.Save();
    }

    //Loads mission progress from PlayerPrefs.
    MissionProgress LoadPlayer_MissionData(){
        string jsonData = PlayerPrefs.GetString(player_missionData, "{}"); // Details were stored as "PlayerData"
        return JsonUtility.FromJson<MissionProgress>(jsonData);
    }


    private const string player_RewardsData = "Player_RewardsData";
    //Saves PlayerData to PlayerPrefs.
    private void SavePlayerData(PlayerData data){
        string jsonData = JsonUtility.ToJson(data);
        PlayerPrefs.SetString(player_RewardsData, jsonData); // Details stored as "PlayerData"
        PlayerPrefs.Save();
    }

    //Load player data from PlayerPrefs
    PlayerData LoadPlayerData(){
        string jsonData = PlayerPrefs.GetString(player_RewardsData, "{}"); // Details were stored as "PlayerData"
        return JsonUtility.FromJson<PlayerData>(jsonData);
    }



}
