using System.Linq;
using UnityEngine.InputSystem.Users;
using UnityEngine.InputSystem;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections.Generic;
using static UnityEngine.AudioSettings;
using static UnityEngine.EventSystems.EventTrigger;
using System;


public class PlayerManagerNew : MonoBehaviour
{
    public Button pauseButton;
    public Button resumeButton;
    public Button retryButton;
    public Button quitButton;
    public GameObject joystickButton;
    public GameObject pauseScreen;
    public bool pause;
    public bool retry;
    public Transform spawnPoint1;
    public Transform spawnPoint2;
    bool charactersMovedToSpawnPoints;

    GameStatsManager game_statsManager;
    private GameObject player;
    private GameObject enemy;
    public GameObject rewardsScreen;

    private void Awake()
    {
        //this instntiste the characters from the selection scene
        SelectionOptions.Instance.eventSytem = GameObject.Find("EventManager");
        
        // Skip spawning for Cash System mode - CashSystemManager handles its own team spawning
        if (SelectionOptions.Instance.isCashSystemSelected)
        {
            Debug.Log("[PlayerManagerNew] Skipping SpawnPlayers - Cash System mode uses CashSystemManager.SpawnTeams");
        }
        else
        {
            SelectionOptions.Instance.SpawnPlayers();
        }
        //SelectionOptions.Instance.eventSytem.SetActive(false);        
        pause = false;

        try{
            game_statsManager = (GameObject.Find("GameStatsManager")).GetComponent<GameStatsManager>();
            //Debug.Log("GameStatsManager");

        }catch(Exception e){
            Debug.Log("Error: " + e.ToString());
        }
    }


    AudioSource audioSource;
    void Start()
    {        
        retry = false;
        charactersMovedToSpawnPoints = false;

        if (UnityEngine.Application.platform == RuntimePlatform.Android ||
           UnityEngine.Application.platform == RuntimePlatform.IPhonePlayer)
        {
            InitializeMobileIngameUI();
        }
        audioSource = GetComponent<AudioSource>();
        LoadAudioSetings();
        audioSource.Play();
        
        enemy = GameObject.FindGameObjectWithTag("Enemy");
        player = GameObject.FindGameObjectWithTag("Player");
    }


    private GameSettings gameSettings;

    private void LoadAudioSetings()
    {
        if (audioSource == null) return;
        
        gameSettings = PlayerPrefs.HasKey(GameSettingsKey) 
            ? LoadGameSettings() 
            : new GameSettings();

        // Ensure volume is not zero (default to 1 if zero or negative)
        float volume = gameSettings.GameplayVolume_value;
        if (volume <= 0f) volume = 1f;
        audioSource.volume = volume;
        Debug.Log($"[PlayerManagerNew] Loaded GameplayVolume_value: {gameSettings.GameplayVolume_value}, Applied: {audioSource.volume}");
    }


    private void Update()
    {
        if (retry)
        {
            retry = false;
            enemy.SetActive(true);
            player.SetActive(true);
            enemy.transform.position = new Vector3(5.32f,0,0);
            player.transform.position = new Vector3(7.32f,0,0);

            player.GetComponent<HealthNew>().ResetHealth();
            enemy.GetComponent<HealthNew>().ResetHealth();
            player.GetComponent<HealthNew>().TakeDamage(0);
            enemy.GetComponent<HealthNew>().TakeDamage(0);
        }

        if (!charactersMovedToSpawnPoints)
            MoveCharactersToSpawnPoints();

        MonitorRounds();
    }
    private void InitializeMobileIngameUI()
    {
        pauseButton.onClick.AddListener(Pause);
        joystickButton.gameObject.SetActive(true);

    // NOTE: Block/Dodge buttons are no longer wired here.
    // Attach DeviantMobile.Input.MobileControlManagerAction to the respective UI objects
    // and map tap(s) to the desired Input Actions.
        // This removes direct onClick listeners and unifies mobile input via the Input System.
    }
    // Block/Dodge methods removed. Use MobileControlManager on the UI to trigger Input Actions instead.
    //the below pause, quit, retry, resume,continue, restart functions work only for mobile, for pc they are placed in the healthnew script(due to complex inputsystem required for pc they had to be there)
    public void Pause()
    {
        pause = true;
        pauseScreen.SetActive(true);
        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;
        if (UnityEngine.Application.platform == RuntimePlatform.Android ||
           UnityEngine.Application.platform == RuntimePlatform.IPhonePlayer)
        {
            resumeButton.onClick.AddListener(Resume);
            retryButton.onClick.AddListener(Retry);
            quitButton.onClick.AddListener(Quit);
        }
    }
    
    public void Resume()
    {
        pause = false;
        Time.timeScale = 1f;
        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;
        pauseScreen.SetActive(false);
    }

    public void Continue(){
        game_statsManager.match_end(); //Go to Home
        game_statsManager.addMatch();
    }
    
    public void Quit()
    {
        // game_statsManager.match_end();
        //Reset Missions
        // game_statsManager.ResetCompletedMissions();
        // game_statsManager.addMatch();
        
        game_statsManager.match_quit(); //Go to Home

        // SceneManager.LoadSceneAsync(1);
    }

    public void Retry()
    {
        pause = false;
        retry = true;
        player.GetComponent<RoundsScript>().currentRound = 0;
        player.GetComponent<RoundsScript>().playerWins = 0; player.GetComponent<RoundsScript>().enemyWins = 0; player.GetComponent<RoundsScript>().roundsToPlay = 3;
        enemy.GetComponent<RoundsScript>().currentRound = 0;
        enemy.GetComponent<RoundsScript>().playerWins = 0; enemy.GetComponent<RoundsScript>().enemyWins = 0; enemy.GetComponent<RoundsScript>().roundsToPlay = 3;
        enemy.GetComponent<StaminaSystem>().currentStamina = 100;
        player.GetComponent<StaminaSystem>().currentStamina = 100;
        player.GetComponent<RoundsScript>().isRoundActive = false;
        enemy.GetComponent<RoundsScript>().isRoundActive = false;
        rewardsScreen.SetActive(false);
        pauseScreen.SetActive(false);
        // just reinforce and make sure the characters are active, if not active the startneround won't execute well, especially the coroutines in the player
        enemy.SetActive(true);
        player.SetActive(true);
        player.GetComponent<RoundsScript>().StartNewRound();

        //Reset Missions
        // game_statsManager.ResetCompletedMissions();
        game_statsManager.ResetMissions_onRetry();
    }


    public void MoveCharactersToSpawnPoints()
    {
        if (charactersMovedToSpawnPoints) return;

        // Find game objects with tags "Enemy" and "Player"
        GameObject enemy = GameObject.FindGameObjectWithTag("Enemy");
        GameObject player = GameObject.FindGameObjectWithTag("Player");

        if (enemy != null && player != null)
        {
            // Set initial positions
            enemy.transform.position = new Vector3(5.32f, 0, 0);
            player.transform.position = new Vector3(7.32f, 0, 0);

            // Make player face the enemy
            player.transform.LookAt(enemy.transform);

            charactersMovedToSpawnPoints = true;
        }
        else
        {
            Debug.LogWarning("Waiting for players to spawn...");
        }
    }


    private void MonitorRounds()
    {
         if (pause || player == null || enemy == null) return;

        // Cache components safely
        var playerRounds = player.GetComponent<RoundsScript>();
        var enemyRounds = enemy.GetComponent<RoundsScript>();
        var playerHealth = player.GetComponent<HealthNew>();
        var enemyHealth = enemy.GetComponent<HealthNew>();

        if (playerRounds == null || enemyRounds == null || playerHealth == null || enemyHealth == null)
        {
            return;
        }

        if (playerRounds.IsTimerMode())
        {
            if (playerRounds.isRoundActive)
            {
                //only player updates the timer
                playerRounds.currentTime -= Time.deltaTime;
                playerRounds.UpdateTimerText();

                if (playerRounds.currentTime <= 0f)
                {
                    StartCoroutine(playerRounds.EndRound());
                }

                if (playerHealth.isDead)
                {
                    playerHealth.isDead = false;
                    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;
                    enemyRounds.enemyWins++;
                    playerRounds.enemyWins++;
                    
                    StartCoroutine(playerRounds.RespawnDeadPlayer(GameObject.FindGameObjectWithTag("Player")));

                }
                else if (enemyHealth.isDead)
                {
                    enemyHealth.isDead = false;
                    playerRounds.playerWins++;
                    enemyRounds.playerWins++;
                    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;
                    StartCoroutine(enemyRounds.RespawnDeadPlayer(GameObject.FindGameObjectWithTag("Enemy")));
                }
            }
           

        }
        else
        {
            //this works for kill mode 
            // Check for round end conditions, such as health reaching zero

            if (playerRounds.isRoundActive && playerHealth.isDead)
            {
                playerHealth.isDead = false;
                enemyRounds.enemyWins++;
                playerRounds.enemyWins++;                
                StartCoroutine(playerRounds.EndRound());
            }
            else if (enemyRounds.isRoundActive && enemyHealth.isDead)
            {
                enemyHealth.isDead = false;
                playerRounds.playerWins++;
                enemyRounds.playerWins++;
                //use player(instead of enemy) since it's the one responsible for rounds
                StartCoroutine(playerRounds.EndRound());
            }
            
        }
    }

    #region
        private const string GameSettingsKey = "GameSettings";
        public static void SaveGameSettings(GameSettings settings){
            string json = JsonUtility.ToJson(settings);
            PlayerPrefs.SetString(GameSettingsKey, json);
            PlayerPrefs.Save();
        }

        public static GameSettings LoadGameSettings(){
            if (PlayerPrefs.HasKey(GameSettingsKey))
            {
                string json = PlayerPrefs.GetString(GameSettingsKey);
                return JsonUtility.FromJson<GameSettings>(json);
            }
            return new GameSettings(); // Return default settings if none are saved
        }

    #endregion
}