using System.Collections.Generic;
using Intrepid.GameManagers;
using Intrepid.Gameplay.Entities.Player.PDA.Inputs;
using Intrepid.Sound;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Intrepid.Gameplay.Entities.Player.PDA.UI.Applications.MusicPlayer
{
    public class PDAMusicSelectionUI : MonoBehaviour
    {
        [SerializeField] private TextMeshProUGUI textMesh;
        [SerializeField] private Button selected;
        [SerializeField] private Button previous;
        [SerializeField] private Button next;

        private List<SoundMusicData> Musics { get; } = new();
        private int Index { get; set; }
        
        public SoundMusicData SelectedMusic => Musics.Count == 0 ? null : Musics[Index];

        public void WhenStarting()
        {
        }

        public void WhenFinishing()
        {
            Index = 0;
            Musics.Clear();
            textMesh.text = "-";
            selected.interactable = false;
            previous.interactable = false;
            next.interactable = false;
        }
        
        public void UpdateApplication(PDAInputs inputs)
        {
            if (inputs.DPad.Up())
            {
                Index = 0;
                DisplayText();
            }

            if (inputs.DPad.Left())
            {
                GoPrevious();
            }
            
            if (inputs.DPad.Right())
            {
                GoNext();
            }
        }

        public void Feed(List<SoundMusicData> musicKnown)
        {
            Index = 0;
            Musics.Clear();
            switch (musicKnown.Count)
            {
                case 0:
                    textMesh.text = "-";
                    selected.interactable = false;
                    previous.interactable = false;
                    next.interactable = false;
                    return;
                case 1:
                    selected.interactable = true;
                    previous.interactable = false;
                    next.interactable = false;
                    break;
                default:
                    selected.interactable = true;
                    previous.interactable = true;
                    next.interactable = true;
                    break;
            }
            Musics.Capacity = musicKnown.Count;
            Musics.AddRange(musicKnown);
            DisplayText();
        }
        
        private void DisplayText()
        {
            textMesh.text = Proxy.Instance.I18N.Localise(Musics[Index].Localization);
        }

        public void GoPrevious()
        {
            if (Musics.Count == 0) return;
            if (--Index < 0) Index = Musics.Count - 1;
            DisplayText();
        }

        public void GoNext()
        {
            if (Musics.Count == 0) return;
            if (++Index >= Musics.Count) Index = 0;
            DisplayText();
        }
    }
}