using UnityEngine;
using UnityEngine.UI;
using TMPro;
using FishNet;
using IStalk.Core;
using IStalk.Data;
using IStalk.Runner;
using IStalk.Shared;

namespace IStalk.UI
{
    public class RunnerHUD : MonoBehaviour
    {
        [Header("Weight")]
        [SerializeField] private Slider _weightBar;
        [SerializeField] private TextMeshProUGUI _weightText;
        [SerializeField] private Image _weightBarFill;
        [SerializeField] private Color _lightColor = Color.green;
        [SerializeField] private Color _heavyColor = Color.red;

        [Header("Inventory")]
        [SerializeField] private Transform _slotContainer;
        [SerializeField] private GameObject _slotPrefab;
        [SerializeField] private TextMeshProUGUI _lootValueText;

        [Header("Match")]
        [SerializeField] private TextMeshProUGUI _matchTimerText;
        [SerializeField] private TextMeshProUGUI _stateText;
        [SerializeField] private Slider _extractionProgress;
        [SerializeField] private TextMeshProUGUI _extractionText;

        [Header("Interaction")]
        [SerializeField] private GameObject _interactPrompt;
        [SerializeField] private TextMeshProUGUI _interactText;

        private PlayerInventory _inventory;
        private WeightComponent _weight;
        private ExtractionManager _extraction;
        private GlobalRules_SO Rules => GlobalRules_SO.Instance;

        private void Start()
        {
            if (_interactPrompt != null)
                _interactPrompt.SetActive(false);
        }

        public void Initialize(PlayerInventory inventory, WeightComponent weight)
        {
            _inventory = inventory;
            _weight = weight;
            _extraction = FindAnyObjectByType<ExtractionManager>();

            _inventory.OnInventoryChanged += RefreshInventory;
            _weight.OnWeightChanged += RefreshWeight;

            if (GameManager.Instance != null)
                GameManager.Instance.OnStateChanged += RefreshState;

            RefreshInventory();
            RefreshWeight(0, WeightTier.Naked);
        }

        private void Update()
        {
            if (GameManager.Instance == null) return;

            float timer = GameManager.Instance.MatchTimer;
            int minutes = Mathf.FloorToInt(timer / 60f);
            int seconds = Mathf.FloorToInt(timer % 60f);
            if (_matchTimerText != null)
                _matchTimerText.text = $"{minutes:00}:{seconds:00}";

            if (_extractionProgress != null && _extraction != null)
            {
                _extractionProgress.value = (float)_extraction.TeamLootDeposited / _extraction.ExtractionThreshold;
                if (_extractionText != null)
                    _extractionText.text = $"{_extraction.TeamLootDeposited}/{_extraction.ExtractionThreshold}";
            }
        }

        private void RefreshInventory()
        {
            if (_lootValueText != null)
                _lootValueText.text = $"Loot: {_inventory.TotalLootValue}";
        }

        private void RefreshWeight(float currentWeight, WeightTier tier)
        {
            if (_weightBar != null)
            {
                _weightBar.value = currentWeight / Rules.weightThresholdOverloaded;
            }
            if (_weightText != null)
            {
                _weightText.text = $"{currentWeight:F1}kg ({tier})";
            }
            if (_weightBarFill != null)
            {
                _weightBarFill.color = Color.Lerp(_lightColor, _heavyColor, _weightBar.value);
            }
        }

        private void RefreshState(MatchState state)
        {
            if (_stateText != null)
            {
                _stateText.text = state switch
                {
                    MatchState.GracePeriod => "GRACE PERIOD",
                    MatchState.Hunt => "HUNT",
                    MatchState.Overtime => "OVERTIME",
                    MatchState.RunnersWin => "ESCAPED!",
                    MatchState.EyeWins => "CAUGHT...",
                    _ => ""
                };
            }
        }

        public void ShowInteractPrompt(string text)
        {
            if (_interactPrompt != null) _interactPrompt.SetActive(true);
            if (_interactText != null) _interactText.text = text;
        }

        public void HideInteractPrompt()
        {
            if (_interactPrompt != null) _interactPrompt.SetActive(false);
        }

        private void OnDestroy()
        {
            if (_inventory != null) _inventory.OnInventoryChanged -= RefreshInventory;
            if (_weight != null) _weight.OnWeightChanged -= RefreshWeight;
            if (GameManager.Instance != null) GameManager.Instance.OnStateChanged -= RefreshState;
        }
    }
}
