using System;
using UnityEngine;
using UnityEngine.UI;

namespace Minesweeper.Presentation.Views
{
    public sealed class PauseView : MonoBehaviour, IPauseView
    {
        [SerializeField] private GameObject root;
        [SerializeField] private Button restartButton;
        [SerializeField] private Button resumeButton;
        [SerializeField] private Button mainMenuButton;

        public event Action RestartRequested;
        public event Action ResumeRequested;
        public event Action GoToMenuRequested;

        private GameObject Root => root != null ? root : gameObject;

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

        private void OnEnable()
        {
            AddListeners();
        }

        private void OnDisable()
        {
            RemoveListeners();
        }

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

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

        private void AddListeners()
        {
            if (restartButton != null)
            {
                restartButton.onClick.AddListener(OnRestartClicked);
            }

            if (resumeButton != null)
            {
                resumeButton.onClick.AddListener(OnResumeClicked);
            }

            if (mainMenuButton != null)
            {
                mainMenuButton.onClick.AddListener(OnMainMenuClicked);
            }
        }

        private void RemoveListeners()
        {
            if (restartButton != null)
            {
                restartButton.onClick.RemoveListener(OnRestartClicked);
            }

            if (resumeButton != null)
            {
                resumeButton.onClick.RemoveListener(OnResumeClicked);
            }

            if (mainMenuButton != null)
            {
                mainMenuButton.onClick.RemoveListener(OnMainMenuClicked);
            }
        }

        private void OnRestartClicked()
        {
            RestartRequested?.Invoke();
        }

        private void OnResumeClicked()
        {
            ResumeRequested?.Invoke();
        }

        private void OnMainMenuClicked()
        {
            GoToMenuRequested?.Invoke();
        }
    }
}
