using FishNet;
using FishNet.Object;
using FishNet.Object.Synchronizing;
using UnityEngine;
using IStalk.Data;
using IStalk.Runner;

namespace IStalk.Core
{
    public class Shrine : NetworkBehaviour
    {
        [SerializeField] private float _interactRadius = 2.5f;
        [SerializeField] private Transform _itemDisplayPoint;

        private readonly SyncList<string> _availableItems = new();

        public override void OnStartServer()
        {
            base.OnStartServer();
            PopulateStock();
        }

        [Server]
        private void PopulateStock()
        {
            var allShrineItems = Resources.LoadAll<ShrineItemData_SO>("Items/Shrine");
            foreach (var item in allShrineItems)
                _availableItems.Add(item.itemId);
        }

        [Server]
        public bool TryPurchase(PlayerInventory buyerInventory, string shrineItemId)
        {
            if (!_availableItems.Contains(shrineItemId)) return false;

            var data = ItemDatabase.Instance.GetShrineItem(shrineItemId);
            if (data == null) return false;

            if (buyerInventory.TotalLootValue < data.lootCost) return false;

            int remaining = data.lootCost;
            var items = buyerInventory.GetItems();
            for (int i = items.Count - 1; i >= 0 && remaining > 0; i--)
            {
                var lootData = ItemDatabase.Instance.GetLootItem(items[i]);
                if (lootData == null) continue;
                remaining -= lootData.lootValue;
                buyerInventory.TryRemoveItem(items[i]);
            }

            var effect = buyerInventory.GetComponent<ShrineItemEffect>();
            if (effect != null)
                effect.ApplyEffect(data);

            PlayPurchaseObservers(shrineItemId);
            return true;
        }

        [ObserversRpc]
        private void PlayPurchaseObservers(string itemId)
        {
            var data = ItemDatabase.Instance.GetShrineItem(itemId);
            if (data != null && data.activationSound != null)
                AudioSource.PlayClipAtPoint(data.activationSound, transform.position);
        }

        public bool IsPlayerInRange(Vector3 playerPos)
        {
            return Vector3.Distance(transform.position, playerPos) <= _interactRadius;
        }

        public ShrineItemData_SO[] GetAvailableItems()
        {
            var result = new ShrineItemData_SO[_availableItems.Count];
            for (int i = 0; i < _availableItems.Count; i++)
                result[i] = ItemDatabase.Instance.GetShrineItem(_availableItems[i]);
            return result;
        }
    }
}
