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

namespace Minesweeper.Presentation.Views
{
    public sealed class TopPanelView : MonoBehaviour, ITopPanelView
    {
        [SerializeField] private GameObject root;
        [SerializeField] private TMP_Text mineText;
        [SerializeField] private TMP_Text timerText;
        [SerializeField] private Button smileButton;
        [SerializeField] private Image smileImage;
        [SerializeField] private MinesweeperUiConfig uiConfig;

        public event Action SmileClicked;

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

        private void OnEnable()
        {
            if (smileButton != null)
            {
                smileButton.onClick.AddListener(OnSmileClicked);
            }
        }

        private void OnDisable()
        {
            if (smileButton != null)
            {
                smileButton.onClick.RemoveListener(OnSmileClicked);
            }
        }

        public void SetActive(bool active)
        {
            root.SetActive(active);
        }

        public void SetRemainingMines(int remainingMines)
        {
            if (mineText != null)
            {
                mineText.text = Mathf.Max(0, remainingMines).ToString("00000");
            }
        }

        public void SetTimer(float seconds)
        {
            if (timerText != null)
            {
                timerText.text = Mathf.FloorToInt(seconds).ToString("00000");
            }
        }

        public void SetSmile(SmileFaceState state)
        {
            if (smileImage == null || uiConfig == null)
            {
                return;
            }

            var sprite = uiConfig.GetSmileSprite(state);
            if (sprite != null)
            {
                smileImage.sprite = sprite;
            }

            smileImage.color = Color.white;
        }

        public void BindConfig(MinesweeperUiConfig config)
        {
            uiConfig = config;
        }

        private void OnSmileClicked()
        {
            SmileClicked?.Invoke();
        }
    }
}
