using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Game
{
	public class TextChoiceModule : MonoBehaviour
	{
		public const float ButtonTimeGap = 0.2f;
		
		[SerializeField] private ScreenController screenController;
		[SerializeField] private TextChoiceButton buttonPrefab;
		[SerializeField] private VerticalLayoutGroup buttonGroup;
		[SerializeField] private int maxButtonCount;
		
		private List<TextChoiceButton> buttons = new List<TextChoiceButton>();
		private TextChoiceButton lastSelectedButton;
		
		private void Awake()
		{
			for (int i = 0; i < maxButtonCount; i++)
			{
				var button = Instantiate(buttonPrefab, buttonGroup.transform);
				buttons.Add(button);
				
				button.Clicked += ChoiceSelected;
				button.Deactivate(0);
			}
		}

		private void ChoiceSelected(TextChoiceButton choiceButton)
		{
			if (screenController.IsScreenLoading)
				return;
			
			lastSelectedButton = choiceButton;
			var choice = screenController.CurrentScreen.Choices[buttons.IndexOf(choiceButton)];
			screenController.LoadScreen(choice.nextScreen);
			choice.OnSelected();
		}

		public void Activate()
		{
			StopAllCoroutines();
			StartCoroutine(Activating());
		}

		private IEnumerator Activating()
		{
			if(screenController.CurrentScreen.ModulesCount > 1)
				yield return new WaitForSeconds(ButtonTimeGap);

			for (int i = 0; i < screenController.CurrentScreen.Choices.Count; i++)
			{
				if (i > buttons.Count - 1)
					continue;
				
				buttons[i].gameObject.SetActive(true);
			}

			for (int i = 0; i < screenController.CurrentScreen.Choices.Count; i++)
			{
				if (i > buttons.Count - 1)
					continue;
				
				buttons[i].Activate(screenController.CurrentScreen.Choices[i].text, screenController.CurrentTextColor);
				yield return new WaitForSeconds(ButtonTimeGap);
			}
		}

		public void Deactivate()
		{
			StopAllCoroutines();
			StartCoroutine(Deactivating());
		}

		private IEnumerator Deactivating()
		{
			foreach (var button in buttons)
			{
				if(button == lastSelectedButton)
					continue;
				
				button.Deactivate(ScreenController.FadeOutDuration);
			}
			
			yield return new WaitForSeconds(ScreenController.FadeOutDuration * 0.5f);
			
			if(lastSelectedButton != null)
				lastSelectedButton.Deactivate(ScreenController.FadeOutDuration * 0.5f);
			
			yield return new WaitForSeconds(ScreenController.FadeOutDuration * 0.5f);
			foreach (var button in buttons)
				button.gameObject.SetActive(false);
		}
	}
}