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

namespace Minesweeper.Presentation.Views
{
    public sealed class ResultView : MonoBehaviour, IResultView
    {
        [SerializeField] private GameObject root;
        [SerializeField] private Button restartButton;
        [SerializeField] private Button mainMenuButton;
        [SerializeField] private TMP_Text resultText;

        public event Action RestartRequested;
        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(GameState state)
        {
            Root.SetActive(true);
            if (resultText != null)
            {
                resultText.text = state == GameState.Won ? "YOU WIN" : "GAME OVER";
            }
        }

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

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

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

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

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

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

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