using System;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using YachtDice.Categories;

namespace YachtDice.UI
{
    public class ScoreCardView : MonoBehaviour
    {
        [Header("Category Rows (порядок соответствует каталогу)")]
        [SerializeField] private List<CategoryRowView> categoryRows = new();

        [Header("Summary")]
        [SerializeField] private TMP_Text upperSumText;
        [SerializeField] private TMP_Text upperBonusText;
        [SerializeField] private TMP_Text totalScoreText;

        public event Action<CategoryDefinition> OnCategorySelected;

        private CategoryCatalog catalog;
        private Dictionary<CategoryDefinition, int> categoryToRowIndex;

        /// <summary>
        /// Инициализирует скоркарту из каталога категорий.
        /// Вызывается из GameController после DI.
        /// </summary>
        public void Initialize(CategoryCatalog categoryCatalog)
        {
            catalog = categoryCatalog;
            categoryToRowIndex = new Dictionary<CategoryDefinition, int>();

            var all = catalog.All;
            int count = Mathf.Min(categoryRows.Count, all.Count);

            for (int i = 0; i < count; i++)
            {
                categoryRows[i].Initialize(all[i]);
                categoryRows[i].OnCategorySelected += HandleCategorySelected;
                categoryToRowIndex[all[i]] = i;
            }

            UpdateTotalDisplay(0, 0, false);
        }

        public void UpdatePreviews(Dictionary<CategoryDefinition, int> previews)
        {
            foreach (var kvp in previews)
            {
                if (categoryToRowIndex.TryGetValue(kvp.Key, out int rowIndex))
                {
                    categoryRows[rowIndex].ShowPreview(kvp.Value);
                    categoryRows[rowIndex].SetInteractable(true);
                }
            }
        }

        public void ClearAllPreviews()
        {
            for (int i = 0; i < categoryRows.Count; i++)
            {
                categoryRows[i].HidePreview();
                categoryRows[i].SetInteractable(false);
            }
        }

        public void SetCategoryScored(CategoryDefinition category, int score)
        {
            if (categoryToRowIndex.TryGetValue(category, out int index))
                categoryRows[index].SetRecordedScore(score);
        }

        public void SetAllInteractable(bool interactable)
        {
            for (int i = 0; i < categoryRows.Count; i++)
                categoryRows[i].SetInteractable(interactable);
        }

        public void UpdateTotalDisplay(int totalScore, int upperSum, bool hasUpperBonus)
        {
            totalScoreText.text = totalScore.ToString();
            upperSumText.text = $"{upperSum} / 63";
            upperBonusText.text = hasUpperBonus ? "+35" : "---";
        }

        public void ResetAll()
        {
            for (int i = 0; i < categoryRows.Count; i++)
                categoryRows[i].ResetRow();

            UpdateTotalDisplay(0, 0, false);
        }

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

        private void OnDestroy()
        {
            for (int i = 0; i < categoryRows.Count; i++)
                categoryRows[i].OnCategorySelected -= HandleCategorySelected;
        }
    }
}
