using System;
using Minesweeper.Core;
using UnityEngine;
using UnityEngine.UI;

namespace Minesweeper.Presentation.Views
{
    public sealed class MainMenuView : MonoBehaviour, IMainMenuView
    {
        [SerializeField] private GameObject root;
        [SerializeField] private Button startButton;
        [SerializeField] private MenuSliderView sizeXSlider = new MenuSliderView();
        [SerializeField] private MenuSliderView sizeYSlider = new MenuSliderView();
        [SerializeField] private MenuSliderView minesSlider = new MenuSliderView();

        public event Action StartClicked;
        public event Action SizeChanged;

        public GameSettingsValue SelectedSettings => new GameSettingsValue(sizeXSlider.Value, sizeYSlider.Value, minesSlider.Value);

        private void Awake()
        {
            if (root == null)
            {
                root = gameObject;
            }
        }

        private void OnEnable()
        {
            if (startButton != null)
            {
                startButton.onClick.AddListener(OnStartClicked);
            }

            sizeXSlider.ValueChanged += OnSizeSliderChanged;
            sizeYSlider.ValueChanged += OnSizeSliderChanged;
            sizeXSlider.AddListeners();
            sizeYSlider.AddListeners();
            minesSlider.AddListeners();
        }

        private void OnDisable()
        {
            if (startButton != null)
            {
                startButton.onClick.RemoveListener(OnStartClicked);
            }

            sizeXSlider.RemoveListeners();
            sizeYSlider.RemoveListeners();
            minesSlider.RemoveListeners();
            sizeXSlider.ValueChanged -= OnSizeSliderChanged;
            sizeYSlider.ValueChanged -= OnSizeSliderChanged;
        }

        public void Show()
        {
            root.SetActive(true);
        }

        public void Hide()
        {
            root.SetActive(false);
        }

        public void ConfigureSizeX(int min, int max, int value)
        {
            sizeXSlider.Configure(min, max, value, "Size X");
        }

        public void ConfigureSizeY(int min, int max, int value)
        {
            sizeYSlider.Configure(min, max, value, "Size Y");
        }

        public void ConfigureMines(int min, int max, int value)
        {
            minesSlider.Configure(min, max, value, "Mines Count");
        }

        private void OnStartClicked()
        {
            StartClicked?.Invoke();
        }

        public void BindRoot(GameObject root)
        {
            this.root = root != null ? root : gameObject;
        }

        private void OnSizeSliderChanged(int value)
        {
            SizeChanged?.Invoke();
        }
    }
}
