using FishNet.Object;
using FishNet.Object.Synchronizing;
using UnityEngine;

namespace IStalk.Core
{
    public class RoomSeal : NetworkBehaviour
    {
        [SerializeField] private Collider _sealBarrier;
        [SerializeField] private Renderer _sealVisual;
        [SerializeField] private ParticleSystem _sealVfx;
        [SerializeField] private AudioClip _sealSound;
        [SerializeField] private float _fadeInDuration = 2f;

        private readonly SyncVar<bool> _isSealed = new();
        private float _fadeProgress;
        private Material _sealMaterial;

        public bool IsSealed => _isSealed.Value;

        public override void OnStartClient()
        {
            base.OnStartClient();
            _isSealed.OnChange += OnSealChanged;

            if (_sealBarrier != null) _sealBarrier.enabled = false;
            if (_sealVisual != null)
            {
                _sealMaterial = _sealVisual.material;
                SetAlpha(0f);
                _sealVisual.enabled = false;
            }
        }

        [Server]
        public void Seal()
        {
            if (_isSealed.Value) return;
            _isSealed.Value = true;
            if (_sealBarrier != null) _sealBarrier.enabled = true;
            PlaySealEffectsObservers();
        }

        private void Update()
        {
            if (!IsClientStarted) return;
            if (!_isSealed.Value || _sealMaterial == null) return;

            if (_fadeProgress < 1f)
            {
                _fadeProgress += Time.deltaTime / _fadeInDuration;
                SetAlpha(Mathf.Clamp01(_fadeProgress));
            }
        }

        [ObserversRpc]
        private void PlaySealEffectsObservers()
        {
            if (_sealVisual != null)
            {
                _sealVisual.enabled = true;
                _fadeProgress = 0f;
            }
            if (_sealVfx != null)
                _sealVfx.Play();
            if (_sealSound != null)
                AudioSource.PlayClipAtPoint(_sealSound, transform.position);
        }

        private void OnSealChanged(bool prev, bool next, bool asServer)
        {
            if (next && _sealBarrier != null)
                _sealBarrier.enabled = true;
        }

        private void SetAlpha(float alpha)
        {
            if (_sealMaterial == null) return;
            Color c = _sealMaterial.color;
            c.a = alpha;
            _sealMaterial.color = c;
        }
    }
}
