using UnityEngine;
using TMPro;
using UnityEngine.UI;
using System.Collections;
using Unity.VisualScripting;
using System;


public class RoundsScript : MonoBehaviour
{
    public int roundsToPlay;

    public int playerWins;
    public int enemyWins;
    public int currentRound;

    public TextMeshProUGUI roundInfoText;

    public TextMeshProUGUI timerText;
    public TextMeshProUGUI roundNumberText;

    public bool isRoundActive = false;
    private float roundTimeInSeconds = 85f;
    public float currentTime;

    public Sprite[] roundsImages;
    public Sprite[] winnerIndicatorImages;
    public Sprite[] emptyIndicatorImages;
    public Sprite[] roundWinGraphics;
    public GameObject R1player;
    public GameObject R2player;
    public GameObject R3player;
    public GameObject R1enemy;
    public GameObject R2enemy;
    public GameObject R3enemy;
    public GameObject roundsInfoGraphic;
    public GameObject roundWinGraphic;
    private string enemyname;
    private string playername;


    //Link to Mission Handler Script
    //Initialize the scripts
    MissionHandler mission_handler;
    GameStatsManager game_statsManager;
    void OnEnable(){
        GameObject gamestatsmanager_go = GameObject.Find("GameStatsManager");
        if (gamestatsmanager_go != null) {
            game_statsManager = gamestatsmanager_go.GetComponent<GameStatsManager>();
            mission_handler = gamestatsmanager_go.GetComponent<MissionHandler>();
        } else {
            DevLog.LogWarning("GameStatsManager not found - mission tracking will be disabled");
        }
    }


    private void Start()
    {
        // Skip RoundsScript entirely in Cash System mode - CashSystemManager handles its own game flow
        if (SelectionOptions.Instance != null && SelectionOptions.Instance.isCashSystemSelected)
        {
            DevLog.Log("[RoundsScript] Disabled for Cash System mode - CashSystemManager handles game flow");
            enabled = false;
            
            // Hide any rounds-related UI
            if (roundInfoText != null) roundInfoText.gameObject.SetActive(false);
            if (roundNumberText != null) roundNumberText.gameObject.SetActive(false);
            if (roundsInfoGraphic != null) roundsInfoGraphic.SetActive(false);
            if (roundWinGraphic != null) roundWinGraphic.SetActive(false);
            if (R1player != null) R1player.SetActive(false);
            if (R2player != null) R2player.SetActive(false);
            if (R3player != null) R3player.SetActive(false);
            if (R1enemy != null) R1enemy.SetActive(false);
            if (R2enemy != null) R2enemy.SetActive(false);
            if (R3enemy != null) R3enemy.SetActive(false);
            return;
        }
        
        try
        {
            InitializeUIReferences();

            if (roundWinGraphic != null)
                roundWinGraphic.SetActive(false);

            currentRound = 0;
            playerWins = 0; enemyWins = 0; roundsToPlay = 3;
            isRoundActive = false;

            StartNewRound();
            NameCharacters();
        }
        catch (Exception ex)
        {
            Debug.LogError($"RoundsScript.Start failed: {ex.Message}\n{ex.StackTrace}");
            // Ensure gameplay still starts even if UI lookups fail
            isRoundActive = false;
            StartNewRound();
        }
    }

    public IEnumerator RespawnDeadPlayer(GameObject character)
    {
        if (GameObject.FindGameObjectWithTag("Player").GetComponent<HealthNew>().currentHealth > GameObject.FindGameObjectWithTag("Enemy").GetComponent<HealthNew>().currentHealth)
        {
            //roundInfoText.text = $"{playername} WINS ROUND!";
            //replace the sprtite with appropiate character graphic
            PlaceRoundWinnerGraphic(playername);
        }
        else
        {
            //roundInfoText.text = $"{enemyname} WINS ROUND!";
            PlaceRoundWinnerGraphic(enemyname);
        }
        
        yield return null;
        Time.timeScale = 0f;//pause application for 5sces
        yield return new WaitForSecondsRealtime(5.5f);
        Time.timeScale = 1;//resume application
        roundWinGraphic.SetActive(false);

        if (SelectionOptions.Instance.isAISelected)
            GameObject.FindGameObjectWithTag("Enemy").GetComponent<CharacterAIController>().attack = true;
        else
            GameObject.FindGameObjectWithTag("Enemy").GetComponent<PlayerScript>().attack = true;

        GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().attack = true;
        GameObject.FindGameObjectWithTag("Player").GetComponent<HealthNew>().ResetHealth();
        GameObject.FindGameObjectWithTag("Enemy").GetComponent<HealthNew>().ResetHealth();
        GameObject.FindGameObjectWithTag("Enemy").transform.position = new Vector3(6.32f, 0, 0);
        GameObject.FindGameObjectWithTag("Player").transform.position = new Vector3(7.32f, 0, 0);
    }

    public void StartNewRound()
    {
        try
        {
            if (roundInfoText == null || roundWinGraphic == null)
            {
                Debug.LogError("UI references are null in StartNewRound. Attempting to find them.");
                InitializeUIReferences();
            }
            
            if (roundInfoText != null)
            {
                roundInfoText.gameObject.SetActive(true);
            }
            
            if (roundWinGraphic != null)
            {
                roundWinGraphic.gameObject.SetActive(false);
            }
            
            // make sure this is empty, useful when restarting the gameplay
            GameObject uiObject = GameObject.Find("UI");
            if (uiObject != null && uiObject.transform.childCount > 0)
            {
                Transform child = uiObject.transform.GetChild(0);
                if (child != null && child.childCount > 11)
                {
                    TextMeshProUGUI textComponent = child.GetChild(11).gameObject.GetComponent<TextMeshProUGUI>();
                    if (textComponent != null)
                    {
                        textComponent.text = "";
                    }
                }
            }
        //if this is the first ever round
        if (currentRound == 0 && gameObject.CompareTag("Player"))
        {
            //Start of the game, start of the first round
            int newRound = GetComponent<RoundsScript>().currentRound + 1;
            GetComponent<RoundsScript>().currentRound = newRound;
            GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().currentRound = newRound;
            if (IsTimerMode())
            {
                currentTime = roundTimeInSeconds;
                if (R1player != null) R1player.GetComponent<Image>().sprite = emptyIndicatorImages[0];
                if (R2player != null) R2player.GetComponent<Image>().sprite = emptyIndicatorImages[0];
                if (R3player != null) R3player.GetComponent<Image>().sprite = emptyIndicatorImages[0];
                if (R1enemy != null) R1enemy.GetComponent<Image>().sprite = emptyIndicatorImages[1];
                if (R2enemy != null) R2enemy.GetComponent<Image>().sprite = emptyIndicatorImages[1];
                if (R3enemy != null) R3enemy.GetComponent<Image>().sprite = emptyIndicatorImages[1];
                StartTimerMode();
            }
            else
            {
                StartCoroutine(StartRoundCountdown());
            }
        }
        else if(currentRound > 0)
        {
            if(gameObject.CompareTag("Player"))
            {                
                int newRound = GetComponent<RoundsScript>().currentRound + 1;
                GetComponent<RoundsScript>().currentRound = newRound;
                GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().currentRound = newRound;
                //GameObject.FindGameObjectWithTag("Player").GetComponent<RoundsScript>().currentRound = newRound;
                
                // Check the mode and perform the appropriate actions
                if (IsTimerMode())
                {
                    currentTime = roundTimeInSeconds;
                    StartTimerMode();
                }
                else
                {
                    print("player countdown");
                    StartCoroutine(StartRoundCountdown());
                }
            }
            else if(gameObject.CompareTag("Enemy"))
            {
                // Start of the game, start of the first round
                int newRound = GetComponent<RoundsScript>().currentRound + 1;
                GetComponent<RoundsScript>().currentRound = newRound;
                GameObject.FindGameObjectWithTag("Player").GetComponent<RoundsScript>().currentRound = newRound;
                
                if (IsTimerMode())
                {
                    currentTime = roundTimeInSeconds;
                    StartTimerMode();
                }
                else
                {
                    print("player countdown");
                    StartCoroutine(StartRoundCountdown());
                }
            }
        }        
        
        


        //Link to Mission Handler Script
        //START of each Round
        if (mission_handler != null) {
            mission_handler.StartOfEachRound(currentRound);
        }

        if (currentRound == 1 && game_statsManager != null){ //For the Start of the Match 
            game_statsManager.winsCountedEachMatch();
        }
        //Debug.LogError("XTP Current Round = " + currentRound.ToString());
    
    }
    catch (Exception ex)
    {
        Debug.LogError($"Error in StartNewRound: {ex.Message}\n{ex.StackTrace}");
    }
    }
    
    private void InitializeUIReferences()
    {
        try
        {
            GameObject uiObject = GameObject.Find("UI");
            if (uiObject != null)
            {
                Transform uiParent = uiObject.transform.GetChild(0);
                if (uiParent != null)
                {
                    // Initialize roundInfoText
                    if (uiParent.childCount > 9)
                    {
                        Transform child9 = uiParent.GetChild(9);
                        if (child9 != null)
                        {
                            roundInfoText = child9.GetComponent<TextMeshProUGUI>();
                            
                            // Initialize roundsInfoGraphic and roundWinGraphic
                            if (child9.childCount > 0)
                                roundsInfoGraphic = child9.GetChild(0).gameObject;
                            if (child9.childCount > 1)
                                roundWinGraphic = child9.GetChild(1).gameObject;
                        }
                    }
                    
                    // Initialize timer text
                    if (uiParent.childCount > 12)
                    {
                        Transform child12 = uiParent.GetChild(12);
                        if (child12 != null)
                        {
                            if (child12.childCount > 0)
                            {
                                Transform child0 = child12.GetChild(0);
                                if (child0 != null && child0.childCount > 0)
                                {
                                    timerText = child0.GetChild(0).GetComponent<TextMeshProUGUI>();
                                }
                            }
                            
                            // Initialize round number text
                            if (child12.childCount > 1)
                            {
                                roundNumberText = child12.GetChild(1).GetComponent<TextMeshProUGUI>();
                            }
                            
                            // Initialize player/enemy round indicators
                            if (child12.childCount > 2) R1player = child12.GetChild(2).gameObject;
                            if (child12.childCount > 3) R2player = child12.GetChild(3).gameObject;
                            if (child12.childCount > 4) R3player = child12.GetChild(4).gameObject;
                            if (child12.childCount > 5) R1enemy = child12.GetChild(5).gameObject;
                            if (child12.childCount > 6) R2enemy = child12.GetChild(6).gameObject;
                            if (child12.childCount > 7) R3enemy = child12.GetChild(7).gameObject;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"Failed to initialize UI references: {ex.Message}");
        }
    }

    private void StartTimerMode()
    {
        // Enable the timer UI if it exists (avoid brittle child chains)
        var ui = GameObject.Find("UI");
        if (ui != null && ui.transform.childCount > 0)
        {
            var p0 = ui.transform.GetChild(0);
            if (p0 != null && p0.childCount > 12)
                p0.GetChild(12).gameObject.SetActive(true);
        }

        if (roundNumberText != null)
            roundNumberText.text = $"ROUND {currentRound}";

        currentTime = roundTimeInSeconds;
        StartCoroutine(StartRoundCountdown());
    }

    public void UpdateTimerText()
    {
        if (currentTime > 0)
        {
            int minutes = Mathf.FloorToInt(currentTime / 60);
            int seconds = Mathf.FloorToInt(currentTime % 60);
            timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
        }
        else
        {
            timerText.text = string.Format("{0:00}:{1:00}", 0, 00);
        }
    }

    private System.Collections.IEnumerator StartRoundCountdown()
    {
        NameCharacters();
        if (roundInfoText != null) roundInfoText.text = "";

        if (currentRound > 1 && !GameObject.Find("PlayerManager").GetComponent<PlayerManagerNew>().retry && IsTimerMode())
        {
            if (GameObject.FindGameObjectWithTag("Player").GetComponent<RoundsScript>().playerWins > GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().enemyWins)
            {
                //roundInfoText.text = $"{playername} WINS ROUND!";
                //replace the sprtite with appropiate character graphic
                PlaceRoundWinnerGraphic(playername);
            }
            else
            {
                //roundInfoText.text = $"{enemyname} WINS ROUND!";
                PlaceRoundWinnerGraphic(enemyname);
            }
            Time.timeScale = 0;//pause application for 5sces
            yield return new WaitForSecondsRealtime(5.5f);
            Time.timeScale = 1;//resume application
        }
        else if(currentRound > 1 && !GameObject.Find("PlayerManager").GetComponent<PlayerManagerNew>().retry && !IsTimerMode())
        {
            if (GameObject.FindGameObjectWithTag("Player").GetComponent<HealthNew>().currentHealth > GameObject.FindGameObjectWithTag("Enemy").GetComponent<HealthNew>().currentHealth)
            {
                //roundInfoText.text = $"{playername} WINS ROUND!";
                //replace the sprtite with appropiate character graphic
                PlaceRoundWinnerGraphic(playername);
            }
            else
            {
                //roundInfoText.text = $"{enemyname} WINS ROUND!";
                PlaceRoundWinnerGraphic(enemyname);
            }
            Time.timeScale = 0;//pause application for 5sces
            yield return new WaitForSecondsRealtime(5.5f);
            Time.timeScale = 1;//resume application
        }


        GameObject.FindGameObjectWithTag("Enemy").transform.position = new Vector3(-2.32f, 0, 0);
        GameObject.FindGameObjectWithTag("Player").transform.position = new Vector3(7.32f, 0, 0);
        GameObject.FindGameObjectWithTag("Enemy").GetComponent<HealthNew>().ResetHealth();
        GameObject.FindGameObjectWithTag("Player").GetComponent<HealthNew>().ResetHealth();

        if (roundWinGraphic != null)
            roundWinGraphic.SetActive(false);

        // Safely set round image
        if (roundsInfoGraphic != null && roundsImages != null && roundsImages.Length > 0)
        {
            int idx = Mathf.Clamp(currentRound - 1, 0, roundsImages.Length - 1);
            var img = roundsInfoGraphic.GetComponent<Image>();
            if (img != null) img.sprite = roundsImages[idx];
            roundsInfoGraphic.SetActive(true);
        }

        yield return new WaitForSecondsRealtime(2f);

        if (roundsInfoGraphic != null)
        {
            var img = roundsInfoGraphic.GetComponent<Image>();
            if (img != null) img.sprite = null;
            roundsInfoGraphic.SetActive(false);
        }

        if (roundInfoText != null) roundInfoText.text = "3";
        yield return new WaitForSecondsRealtime(1f);

        if (roundInfoText != null) roundInfoText.text = "2";
        yield return new WaitForSecondsRealtime(1f);

        if (roundInfoText != null) roundInfoText.text = "1";
        yield return new WaitForSecondsRealtime(1f);

        if (roundInfoText != null) roundInfoText.text = "Fight!";
        yield return new WaitForSecondsRealtime(1f);

        if (roundInfoText != null) roundInfoText.text = "";

        isRoundActive = true;
        var enemyRS = GameObject.FindGameObjectWithTag("Enemy")?.GetComponent<RoundsScript>();
        if (enemyRS != null) enemyRS.isRoundActive = true;

        // Enable attacks without using null-conditional on the assignment target
        var enemyGO = GameObject.FindGameObjectWithTag("Enemy");
        var playerGO = GameObject.FindGameObjectWithTag("Player");

        if (SelectionOptions.Instance.isAISelected)
        {
            var enemyAI = enemyGO != null ? enemyGO.GetComponent<CharacterAIController>() : null;
            if (enemyAI != null) enemyAI.attack = true;
        }
        else
        {
            var enemyPlayerScript = enemyGO != null ? enemyGO.GetComponent<PlayerScript>() : null;
            if (enemyPlayerScript != null) enemyPlayerScript.attack = true;
        }

        var playerScript = playerGO != null ? playerGO.GetComponent<PlayerScript>() : null;
        if (playerScript != null) playerScript.attack = true;

        var pH = playerGO != null ? playerGO.GetComponent<HealthNew>() : null;
        var eH = enemyGO != null ? enemyGO.GetComponent<HealthNew>() : null;
        if (pH != null) pH.isDead = false;
        if (eH != null) eH.isDead = false;
    }



    public IEnumerator EndRound()
    {
        if (IsTimerMode())
        {
            if(SelectionOptions.Instance.isAISelected)
                GameObject.FindGameObjectWithTag("Enemy").GetComponent<CharacterAIController>().attack = false;
            else
                GameObject.FindGameObjectWithTag("Enemy").GetComponent<PlayerScript>().attack = false;

            GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().attack = false;
            GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterMovement>().anim.SetFloat("Speed", 0);
            isRoundActive = false;
            GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().isRoundActive = false;
            if (GameObject.FindGameObjectWithTag("Player").GetComponent<RoundsScript>().playerWins > GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().enemyWins)
            {
                if (currentRound == 1)
                {
                    R1player.GetComponent<Image>().sprite = winnerIndicatorImages[0];
                }
                else if (currentRound == 2)
                {
                    R2player.GetComponent<Image>().sprite = winnerIndicatorImages[0];
                }
                else if (currentRound == 3)
                {
                    R3player.GetComponent<Image>().sprite = winnerIndicatorImages[0];
                }
            }
            else if (GameObject.FindGameObjectWithTag("Player").GetComponent<RoundsScript>().playerWins < GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().enemyWins)
            {
                if (currentRound == 1)
                {
                    R1enemy.GetComponent<Image>().sprite = winnerIndicatorImages[1];
                }
                else if (currentRound == 2)
                {
                    R2enemy.GetComponent<Image>().sprite = winnerIndicatorImages[1];
                }
                else if (currentRound == 3)
                {
                    R3enemy.GetComponent<Image>().sprite = winnerIndicatorImages[1];
                }
            }
            //Link to Mission Handler Script
            //END of each Round
            int playerendHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<HealthNew>().currentHealth;
            int enemyendHealth = GameObject.FindGameObjectWithTag("Enemy").GetComponent<HealthNew>().currentHealth;
            //DevLog.LogWarning("CR = " + currentRound.ToString()  + "|| RS!! with Remaining Health = " + playerendHealth + " Enemy Health = " + enemyendHealth);

            string round_status = "round_status", player_character = "char";

            //Player has won
            if (enemyendHealth == 0)
            {
                round_status = "player_won";
                game_statsManager.addWin();
                player_character = GameObject.FindGameObjectWithTag("Player").name;

            }
            else
            {
                round_status = "player_lost";
                game_statsManager.addLoss();
            }
            mission_handler.EndOfEachRound(currentRound, round_status, playerendHealth, 100, player_character, enemyendHealth);
            if (currentRound < roundsToPlay)
                StartNewRound();
            else
            {
                
                if (GameObject.FindGameObjectWithTag("Player").GetComponent<RoundsScript>().playerWins > GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().enemyWins)
                {
                    //roundInfoText.text = $"{playername} WINS ROUND!";
                    //replace the sprtite with appropiate character graphic
                    PlaceRoundWinnerGraphic(playername);
                }
                else
                {
                    //roundInfoText.text = $"{enemyname} WINS ROUND!";
                    PlaceRoundWinnerGraphic(enemyname);
                }
                Time.timeScale = 0;//pause application for 5sces
                yield return new WaitForSecondsRealtime(5.5f);
                Time.timeScale = 1;//resume application
                EndGame();
            }
                
        }
        else
        {
            if(SelectionOptions.Instance.isAISelected)
                GameObject.FindGameObjectWithTag("Enemy").GetComponent<CharacterAIController>().attack = false;
            else
                GameObject.FindGameObjectWithTag("Enemy").GetComponent<PlayerScript>().attack = false;

            GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().attack = false;
            
            isRoundActive = false;
            GameObject.FindGameObjectWithTag("Enemy").GetComponent<RoundsScript>().isRoundActive = false;
            //Link to Mission Handler Script
            //END of each Round
            int playerendHealth = GameObject.FindGameObjectWithTag("Player").GetComponent<HealthNew>().currentHealth;
            int enemyendHealth = GameObject.FindGameObjectWithTag("Enemy").GetComponent<HealthNew>().currentHealth;
            //DevLog.LogWarning("CR = " + currentRound.ToString()  + "|| RS!! with Remaining Health = " + playerendHealth + " Enemy Health = " + enemyendHealth);

            string round_status = "round_status", player_character = "char";

            //Player has won
            if (enemyendHealth == 0)
            {
                round_status = "player_won";
                game_statsManager.addWin();
                player_character = GameObject.FindGameObjectWithTag("Player").name;

            }
            else
            {
                round_status = "player_lost";
                game_statsManager.addLoss();
            }

            mission_handler.EndOfEachRound(currentRound, round_status, playerendHealth, 100, player_character, enemyendHealth);
            /*
            Round 1: CR = 1|| RS!! with Remaining Health = 0 Enemy Health = 66      Enemy Won
            Round 2: CR = 2|| RS!! with Remaining Health = 0 Enemy Health = 70      Enemy Won
            Round 3: CR = 3|| RS!! with Remaining Health = 28 Enemy Health = 0      Player Won
            */
            
            if (currentRound < roundsToPlay)
            {
                StartNewRound();
            }
            else
            {

                if (GameObject.FindGameObjectWithTag("Player").GetComponent<HealthNew>().currentHealth > GameObject.FindGameObjectWithTag("Enemy").GetComponent<HealthNew>().currentHealth)
                {
                    //roundInfoText.text = $"{playername} WINS ROUND!";
                    //replace the sprtite with appropiate character graphic
                    PlaceRoundWinnerGraphic(playername);
                }
                else
                {
                    //roundInfoText.text = $"{enemyname} WINS ROUND!";
                    PlaceRoundWinnerGraphic(enemyname);
                }
                Time.timeScale = 0;//pause application for 5sces
                yield return new WaitForSecondsRealtime(5.5f);
                Time.timeScale = 1;//resume application
                EndGame();
            }


        }

    }

    public bool IsTimerMode()
    {
        if (SelectionOptions.Instance.isTimeSelected)
            return true; 
        return false;
    }

    public void EndGame()
    {
        GetComponent<HealthNew>().OnDeath();
    }

    public void PlaceRoundWinnerGraphic(string name)
    {
        roundWinGraphic.SetActive(true);
        switch (name)
        {
            case "AMIRA":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[1];
                break;
            case "AMON":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[3];
                break;
            case "ZIGGY":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[0];
                break;
            case "HANNIBAL":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[4];
                break;
            case "IMANI":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[5];
                break;
            case "WINDHAM":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[6];
                break;
            case "BAHMAN":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[2];
                break;
            case "ZIGGY NEW":
                roundWinGraphic.GetComponent<Image>().sprite = roundWinGraphics[7];
                break;
        }
    }

    private void NameCharacters()
    {
        GameObject enemyObj = GameObject.FindGameObjectWithTag("Enemy");
        GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
        
        enemyname = enemyObj ? CharacterPrefabManager.Instance.GetCharacterDisplayName(enemyObj) : "UNKNOWN";
        playername = playerObj ? CharacterPrefabManager.Instance.GetCharacterDisplayName(playerObj) : "UNKNOWN";
    }
}
