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

namespace UI
{
    using Managers;

    public class LoginUI : MonoBehaviour
    {
        [SerializeField] private AgencyBaseStatsConfig baseStats;
        [SerializeField] private LogoConfig logoConfig;
        [SerializeField] private TextMeshProUGUI welcomeMessageName;
        [SerializeField] private Button createButton;
        [Header("Agency")]
        [SerializeField] private TMP_InputField agencyNameField;
        [Header("Logo Picker")]
        [SerializeField] private Image logoIcon;
        [SerializeField] private Button prevLogoButton;
        [SerializeField] private Button nextLogoButton;

        private int currentLogoIndex = 0;

        void Start()
        {
            createButton.interactable = false;
            agencyNameField.onValueChanged.AddListener(value =>
            {
                if (value.Trim() == string.Empty)
                {
                    welcomeMessageName.text = "Kroko studio!";
                    return;
                }

                welcomeMessageName.text = value + "!";
                createButton.interactable = value.Trim() != string.Empty;
            });

            createButton.onClick.AddListener(CreateAccount);
            prevLogoButton.onClick.AddListener(PrevLogo);
            nextLogoButton.onClick.AddListener(NextLogo);

            UpdateLogo();
        }

        private void CreateAccount()
        {
            var employees = GameManager.Instance.GenerateEmployees(baseStats.employees);

            var costumes = GameManager.Instance.GenerateCostumes(baseStats.costumes);

            DataManager.Instance.Init(logoConfig.logos[currentLogoIndex].id, agencyNameField.text, baseStats.budget, baseStats.rating, costumes, employees);

            GUIController.Instance.InitTopPanel(logoConfig.logos[currentLogoIndex].icon, agencyNameField.text, baseStats.budget);

            Calendar.Instance.StartCalendar();

            gameObject.SetActive(false);

            GameManager.Instance.GenerateEmployeesFromSave();
            GameManager.Instance.GenerateCostumesFromSave();
            Sound.SoundController.Instance.Play(SoundType.UIClick);
        }

        private void NextLogo()
        {
            currentLogoIndex++;

            if(currentLogoIndex == logoConfig.logos.Count)
                currentLogoIndex = 0;

            UpdateLogo();
            Sound.SoundController.Instance.Play(SoundType.UIClick);
        }

        private void PrevLogo()
        {
            currentLogoIndex--;

            if (currentLogoIndex < 0)
                currentLogoIndex = logoConfig.logos.Count - 1;

            UpdateLogo();
            Sound.SoundController.Instance.Play(SoundType.UIClick);
        }

        private void UpdateLogo() => logoIcon.sprite = logoConfig.logos[currentLogoIndex].icon;
    }
}