using UnityEngine;
using VContainer;
using YachtDice.Categories;
using YachtDice.Economy;
using YachtDice.Modifiers.Runtime;
using YachtDice.Scoring;

namespace YachtDice.Inventory
{
    public class InventoryController : MonoBehaviour
    {
        [SerializeField] private InventoryView inventoryView;

        private InventoryModel model;
        private ScoringSystem scoringSystem;
        private CurrencyBank currencyBank;

        public InventoryModel Model => model;

        [Inject]
        public void Construct(InventoryModel model, ScoringSystem scoringSystem, CurrencyBank currencyBank)
        {
            this.model = model;
            this.scoringSystem = scoringSystem;
            this.currencyBank = currencyBank;
        }

        private void Start()
        {
            inventoryView.OnActivateClicked += HandleActivate;
            inventoryView.OnDeactivateClicked += HandleDeactivate;
            inventoryView.OnSellClicked += HandleSell;

            model.OnInventoryChanged += HandleInventoryChanged;
            scoringSystem.OnCategoryConfirmed += HandleCategoryConfirmed;

            RefreshView();
        }

        private void OnDestroy()
        {
            if (inventoryView != null)
            {
                inventoryView.OnActivateClicked -= HandleActivate;
                inventoryView.OnDeactivateClicked -= HandleDeactivate;
                inventoryView.OnSellClicked -= HandleSell;
            }

            if (model != null)
                model.OnInventoryChanged -= HandleInventoryChanged;

            if (scoringSystem != null)
                scoringSystem.OnCategoryConfirmed -= HandleCategoryConfirmed;
        }

        public void ToggleVisibility()
        {
            if (inventoryView == null) return;

            if (inventoryView.IsVisible)
                inventoryView.Hide();
            else
                inventoryView.Show();
        }

        private void HandleActivate(ModifierInstance instance)
        {
            model.TryActivate(instance);
        }

        private void HandleDeactivate(ModifierInstance instance)
        {
            model.Deactivate(instance);
        }

        private void HandleSell(ModifierInstance instance)
        {
            if (instance.Definition == null) return;

            int sellPrice = instance.Definition.SellPrice;
            model.RemoveModifier(instance);

            if (currencyBank != null)
                currencyBank.Add(sellPrice);
        }

        private void HandleInventoryChanged()
        {
            RefreshView();
        }

        private void HandleCategoryConfirmed(CategoryDefinition category, ScoreResult result)
        {
            model.ConsumeUseOnActive();
        }

        private void RefreshView()
        {
            if (inventoryView != null && model != null)
                inventoryView.Refresh(model.OwnedModifiers, model.MaxActiveSlots);
        }
    }
}
