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

namespace IStalk.Runner
{
    public class RunnerRevive : NetworkBehaviour
    {
        [SerializeField] private float _reviveRadius = 2f;
        [SerializeField] private float _reviveTime = 4f;
        [SerializeField] private LayerMask _runnerLayer;

        private float _reviveProgress;
        private RunnerHealth _targetHealth;
        private RunnerHealth _myHealth;

        public float ReviveProgress => _reviveProgress;
        public bool IsReviving => _targetHealth != null;

        public override void OnStartClient()
        {
            base.OnStartClient();
            if (!IsOwner)
            {
                enabled = false;
                return;
            }
            _myHealth = GetComponent<RunnerHealth>();
        }

        private void Update()
        {
            if (!IsOwner) return;
            if (_myHealth != null && _myHealth.IsDown) return;

            if (Input.GetKey(KeyCode.R))
            {
                if (_targetHealth == null)
                    FindDownedRunner();

                if (_targetHealth != null)
                {
                    _reviveProgress += Time.deltaTime / _reviveTime;
                    if (_reviveProgress >= 1f)
                    {
                        ServerRevive(_targetHealth.NetworkObject);
                        _reviveProgress = 0;
                        _targetHealth = null;
                    }
                }
            }
            else
            {
                _reviveProgress = 0;
                _targetHealth = null;
            }
        }

        private void FindDownedRunner()
        {
            var colliders = Physics.OverlapSphere(transform.position, _reviveRadius, _runnerLayer);
            foreach (var col in colliders)
            {
                if (col.gameObject == gameObject) continue;
                var health = col.GetComponentInParent<RunnerHealth>();
                if (health != null && health.IsDown)
                {
                    _targetHealth = health;
                    return;
                }
            }
        }

        [ServerRpc]
        private void ServerRevive(FishNet.Object.NetworkObject target)
        {
            if (target == null) return;
            var health = target.GetComponent<RunnerHealth>();
            if (health != null && health.IsDown)
            {
                float dist = Vector3.Distance(transform.position, target.transform.position);
                if (dist <= _reviveRadius * 1.5f)
                    health.Revive();
            }
        }
    }
}
