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

namespace IStalk.Eye
{
    public class EyeEyelidController : NetworkBehaviour
    {
        private readonly SyncVar<bool> _eyelidsClosed = new();

        private GameObject _blackOverlay;

        public bool IsClosed => _eyelidsClosed.Value;

        public override void OnStartClient()
        {
            base.OnStartClient();
            _eyelidsClosed.OnChange += OnEyelidStateChanged;

            if (!IsOwner)
            {
                enabled = false;
                return;
            }
            CreateBlackOverlay();
        }

        private void Update()
        {
            if (!IsOwner) return;

            if (Input.GetMouseButtonDown(1))
                ServerSetEyelids(!_eyelidsClosed.Value);
        }

        [ServerRpc]
        private void ServerSetEyelids(bool closed)
        {
            _eyelidsClosed.Value = closed;
        }

        private void OnEyelidStateChanged(bool prev, bool next, bool asServer)
        {
            if (IsOwner && _blackOverlay != null)
                _blackOverlay.SetActive(next);
        }

        private void CreateBlackOverlay()
        {
            var canvas = new GameObject("EyelidOverlay");
            var canvasComp = canvas.AddComponent<Canvas>();
            canvasComp.renderMode = RenderMode.ScreenSpaceOverlay;
            canvasComp.sortingOrder = 999;

            var panel = new GameObject("BlackPanel");
            panel.transform.SetParent(canvas.transform, false);
            var img = panel.AddComponent<UnityEngine.UI.Image>();
            img.color = Color.black;
            var rect = panel.GetComponent<RectTransform>();
            rect.anchorMin = Vector2.zero;
            rect.anchorMax = Vector2.one;
            rect.offsetMin = Vector2.zero;
            rect.offsetMax = Vector2.zero;

            _blackOverlay = canvas;
            _blackOverlay.SetActive(false);
        }

        public override void OnStopClient()
        {
            base.OnStopClient();
            if (_blackOverlay != null)
                Destroy(_blackOverlay);
        }
    }
}
