using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class NetworkedSlash : MonoBehaviour
{
    [Header("Visuals")]
    [SerializeField] private GameObject hitParticlesPrefab;
    [SerializeField] private GameObject visuals;
    [SerializeField] private GameObject hitBox;
    [Header("Physics:")]
    [SerializeField] private LayerMask abilityHitLayer;

    [Header("Set by code")]
    public PhotonView photonView;
    public PhotonView owner;
    public Taggable ownerTag;
    public SimpleMeleeSlashAbility ability;
    public float lifeSpan;
    public float range;
    public bool regenHealthOnHit;
    public bool regenManaOnHit;

    public float healthOnHit;
    public float manaOnHit;

    private Health ownerHealth;
    private Mana ownerMana;

    private PhotonView possibleTarget;
    private Taggable target;
    private List<Taggable> targets = new List<Taggable>();

    private bool waitingForDestroy = false;

    public UnityEvent<Vector3> onTargetHit = new UnityEvent<Vector3>();

    private Vector3 resizedByAbility = new Vector3();
    private Vector3 relocatedHitBox = new Vector3();

    private Collider[] hits;

    private List<GameObject> hitSpawnedVFXs = new List<GameObject>();
    private GameObject hitSpawnedVFX;
    private Vector3 hitPositionCorrected;


    private void Awake()
    {
        photonView = GetComponent<PhotonView>();
        onTargetHit.AddListener(SpawnHitParticleVFX);
    }

    public void Init()
    {
        waitingForDestroy = false;

        if (photonView.IsMine)
        {
            relocatedHitBox = hitBox.transform.localPosition;
            resizedByAbility = hitBox.transform.localScale;
            resizedByAbility.z = range;
            relocatedHitBox.z = range / 2;

            hitBox.transform.localScale = resizedByAbility;
            hitBox.transform.localPosition = relocatedHitBox;

            photonView.RPC(nameof(RPC_RemoteInit), RpcTarget.Others, AbilityIndexer.Instance.Abilities.IndexOf(ability));

            ownerHealth = owner.GetComponent<Health>();
            ownerMana = owner.GetComponent <Mana>();

            StartCoroutine(SelfDestruct());
            CheckSurroundings();
        }
    }

    [PunRPC]
    private void RPC_RemoteInit(int abilityIndex)
    {
        ability = (SimpleMeleeSlashAbility)AbilityIndexer.Instance.Abilities[abilityIndex];
    }

    [PunRPC]
    private void RPC_DisableVisuals()
    {
        visuals.SetActive(false);
    }

    private void SpawnHitParticleVFX(Vector3 position)
    {
        if (hitParticlesPrefab == null) return;

        hitSpawnedVFX = Instantiate(hitParticlesPrefab, position, this.transform.rotation);
        //hitSpawnedVFX.transform.localScale = visuals.transform.localScale;

        hitSpawnedVFXs.Add(hitSpawnedVFX);
    }

    private void CheckSurroundings()
    {
        hits = Physics.OverlapBox(hitBox.transform.position, hitBox.transform.localScale / 2, this.transform.rotation,  abilityHitLayer);

        foreach (Collider collider in hits)
        {
            Debug.Log("hit collider " + collider.name);

            possibleTarget = collider.GetComponentInParent<PhotonView>();
            if (possibleTarget != null)
                if (possibleTarget == owner) continue;

            target = collider.GetComponentInParent<Taggable>();

            Debug.Log("hit collider, Got taggable: " + target.name);

            if (target == null) continue;

            Debug.Log("hit collider, targetTag: " + target.targetTag.name);

            hitPositionCorrected = target.transform.position;
            hitPositionCorrected.y = this.transform.position.y;
            onTargetHit.Invoke(hitPositionCorrected);

            if (!target.IsValidTarget(ability.targettingTags)) continue;

            Debug.Log("hit collider, added target: " + target.name);
            targets.Add(target);
        }

        foreach (BaseEffect effect in ability.abilityEffects)
        {
            effect.ApplyEffect(ownerTag, targets);
        }

        if (regenHealthOnHit)
            ownerHealth.ChangeValue(healthOnHit * targets.Count);
        if (regenManaOnHit)
            ownerMana.ChangeValue(manaOnHit * targets.Count);
    }

    IEnumerator DelayedDestroy()
    {
        visuals.SetActive(false);

        photonView.RPC(nameof(RPC_DisableVisuals), RpcTarget.Others);

        yield return new WaitForSeconds(1.5f);

        for (int i = hitSpawnedVFXs.Count - 1; i >= 0; i--)
        {
            Destroy(hitSpawnedVFXs[i]);
        }

        yield return new WaitForSeconds(1f);

        PhotonNetwork.Destroy(photonView);
    }

    IEnumerator SelfDestruct()
    {
        yield return new WaitForSeconds(lifeSpan);

        waitingForDestroy = true;

        StartCoroutine(DelayedDestroy());
    }
}
