using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Assets._game.scripts;
using Rewired;
using UnityEngine;
using UnityEngine.UI;

public class Menu : MonoBehaviour
{
    public GameData ClassicGame;
    public List<PlayerData> Planes;
    public Button StartGameButton;
    public Transform PlayerSelectParent;
    public GameObject Managers;
    public Text CountDownLabel;

    public UIPlayerSelectItem PlayerSelect;

    public AudioClip NewTrack;
    public AudioClip Music;

    private List<UIPlayerSelectItem> playerSelectItems = new List<UIPlayerSelectItem>();

    public void Awake()
    {
        if (!GameManager.Instance && Managers)
        {
            Instantiate(Managers);
        }
    }


    public void Start()
    {
        AudioManager.Instance.ChangeBGM(Music);
        NewGame();
        CountDownLabel.text = string.Empty;
    }

    private void SetupPlanes()
    {
        var index = 0;
        foreach (var plane in Planes)
        {
            var playerSelect = Instantiate(PlayerSelect, PlayerSelectParent);
            playerSelect.SelectionChanged += player1 =>
            {
                //StartGameButton.interactable = GameManager.Instance.GameInstance.Players.Count >= 2;
                var count = GameManager.Instance.GameInstance.Players.Count;

                StopCoroutine(StartCountDown());

                if (count >= 1)
                {
                    StartCoroutine(StartCountDown());
                }
                else
                {
                    CountDownLabel.text = string.Empty;
                }
            };

            playerSelect.Setup(plane, index++ * 0.2f);

            playerSelectItems.Add(playerSelect);
        }
    }

    private IEnumerator StartCountDown()
    {
        float endTime = Time.timeSinceLevelLoad + 10;
        int lastInt = -1;

        while (endTime > Time.timeSinceLevelLoad)
        {

            float time = endTime - Time.timeSinceLevelLoad;
            int timeInt = (int)time;
            if (timeInt != lastInt)
            {
                CountDownLabel.text = string.Format("Starting in {0:0}s", time);
            }
            lastInt = (int)time;
            yield return null;
        }
        GameManager.Instance.StartGame();
    }

    public void StartGame()
    {
        GameManager.Instance.StartGame();
        if (NewTrack != null)
        {
            AudioManager.Instance.ChangeBGM(NewTrack);
        }
    }

    public void NewGame()
    {
        GameManager.Instance.NewGame(ClassicGame);
        SetupPlanes();
    }

    void Update()
    {
        var player1 = ReInput.players.GetPlayer(0);
        var player2 = ReInput.players.GetPlayer(1);
        var player3 = ReInput.players.GetPlayer(2);
        var player4 = ReInput.players.GetPlayer(3);

        if (player1.GetButtonDown("Start"))
        {
            AddPlayer(0);
        }
        if (player2.GetButtonDown("Start"))
        {
            AddPlayer(1);
        }
        if (player3.GetButtonDown("Start"))
        {
            AddPlayer(2);
        }
        if (player4.GetButtonDown("Start"))
        {
            AddPlayer(3);
        }

        if (player1.GetButtonDown("Select"))
        {
            ConfirmPlayer(0);
        }
        if (player2.GetButtonDown("Select"))
        {
            ConfirmPlayer(1);
        }
        if (player3.GetButtonDown("Select"))
        {
            ConfirmPlayer(2);
        }
        if (player4.GetButtonDown("Select"))
        {
            ConfirmPlayer(3);
        }

        if (player1.GetNegativeButtonDown("Horizontal0"))
        {
            SelectPreviousPlane(0);
        }
        if (player2.GetNegativeButtonDown("Horizontal0"))
        {
            SelectPreviousPlane(1);
        }
        if (player3.GetNegativeButtonDown("Horizontal0"))
        {
            SelectPreviousPlane(2);
        }
        if (player4.GetNegativeButtonDown("Horizontal0"))
        {
            SelectPreviousPlane(3);
        }

        if (player1.GetButtonDown("Horizontal0"))
        {
            SelectNextPlane(0);
        }
        if (player2.GetButtonDown("Horizontal0"))
        {
            SelectNextPlane(1);
        }
        if (player3.GetButtonDown("Horizontal0"))
        {
            SelectNextPlane(2);
        }
        if (player4.GetButtonDown("Horizontal0"))
        {
            SelectNextPlane(3);
        }
    }

    void ConfirmPlayer(int playerId)
    {
        var currentIndex = playerSelectItems.FindIndex(x => x.CurrentPlayerId == playerId);
        if (currentIndex > -1)
        {
            playerSelectItems[currentIndex].Confirm();
        }
    }

    void AddPlayer(int playerId)
    {
        var currentIndex = playerSelectItems.FindIndex(x => x.CurrentPlayerId == playerId);
        if (currentIndex > -1)
        {
            // Dont do anything if the user has confirmed already
            if (playerSelectItems[currentIndex].isConfirmed)
            {
                return;
            }

            playerSelectItems[currentIndex].Deselect();
        }

        var availablePlane = playerSelectItems.FirstOrDefault(x => x.CurrentPlayerId == -1);
        if (availablePlane != null)
        {
            availablePlane.Select(playerId);
        }
    }

    void SelectNextPlane(int playerId)
    {
        var currentIndex = playerSelectItems.FindIndex(x => x.CurrentPlayerId == playerId);

        // Dont do anything if the user has confirmed already
        if (currentIndex > -1 && playerSelectItems[currentIndex].isConfirmed)
        {
            return;
        }

        for (var i = currentIndex; i < playerSelectItems.Count; i++)
        {
            if (playerSelectItems[i].CurrentPlayerId == -1)
            {
                playerSelectItems[i].Select(playerId);

                if (currentIndex > -1)
                {
                    playerSelectItems[currentIndex].Deselect();
                }

                break;
            }
        }
    }

    void SelectPreviousPlane(int playerId)
    {
        var currentIndex = playerSelectItems.FindIndex(x => x.CurrentPlayerId == playerId);

        // Dont do anything if the user has confirmed already
        if (currentIndex > -1 && playerSelectItems[currentIndex].isConfirmed)
        {
            return;
        }

        for (var i = currentIndex; i >= 0; i--)
        {
            if (playerSelectItems[i].CurrentPlayerId == -1)
            {
                playerSelectItems[i].Select(playerId);

                if (currentIndex > -1)
                {
                    playerSelectItems[currentIndex].Deselect();
                }

                break;
            }
        }
    }
}
