using System;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using YachtDice.Categories;

namespace YachtDice.UI
{
    public class CategoryRowView : MonoBehaviour
    {
        [Header("UI Elements")]
        [SerializeField] private TMP_Text categoryNameText;
        [SerializeField] private TMP_Text previewText;
        [SerializeField] private TMP_Text recordedScoreText;
        [SerializeField] private Button selectButton;
        [SerializeField] private Image background;

        [Header("Colors")]
        [SerializeField] private Color normalColor = new Color(0.95f, 0.95f, 0.95f, 1f);
        [SerializeField] private Color usedColor = new Color(0.75f, 0.75f, 0.75f, 1f);
        [SerializeField] private Color previewPositiveColor = new Color(0.85f, 1f, 0.85f, 1f);
        [SerializeField] private Color previewZeroColor = new Color(1f, 0.88f, 0.88f, 1f);

        private CategoryDefinition category;
        private bool isUsed;

        public event Action<CategoryDefinition> OnCategorySelected;

        public void Initialize(CategoryDefinition categoryDef)
        {
            category = categoryDef;
            isUsed = false;
            categoryNameText.text = categoryDef.DisplayName;
            previewText.text = "";
            recordedScoreText.text = "-";
            selectButton.onClick.AddListener(HandleClick);
            SetInteractable(false);
            background.color = normalColor;
        }

        public void ShowPreview(int previewScore)
        {
            if (isUsed) return;
            previewText.text = previewScore.ToString();
            background.color = previewScore > 0 ? previewPositiveColor : previewZeroColor;
        }

        public void HidePreview()
        {
            if (isUsed) return;
            previewText.text = "";
            background.color = normalColor;
        }

        public void SetRecordedScore(int score)
        {
            isUsed = true;
            recordedScoreText.text = score.ToString();
            previewText.text = "";
            SetInteractable(false);
            background.color = usedColor;
        }

        public void SetInteractable(bool interactable)
        {
            if (isUsed)
            {
                selectButton.interactable = false;
                return;
            }
            selectButton.interactable = interactable;
        }

        public void ResetRow()
        {
            isUsed = false;
            previewText.text = "";
            recordedScoreText.text = "-";
            SetInteractable(false);
            background.color = normalColor;
        }

        private void HandleClick()
        {
            OnCategorySelected?.Invoke(category);
        }

        private void OnDestroy()
        {
            selectButton.onClick.RemoveListener(HandleClick);
        }
    }
}
