using Darkmatter.Core;
using Darkmatter.Domain;
using System;
using UnityEngine;
using VContainer;

namespace Darkmatter.Presentation
{
    public class GunWeapon : WeaponBase
    {
        [Header("VFX")]
        public ParticleSystem MuzzleFlashParticle;
        public ParticleSystem BulletHitEffectParticle;

        [Header("Weapon Data")]
        public float fireRate = 0.1f;
        public override int AmmoCount { get; protected set; } = 40;
        private float lastUsedTime;
        public GameObject BulletHole;   
        public override string WeaponName => "Rifel";


        public override bool canAttack => Time.time >= lastUsedTime + fireRate && AmmoCount > 0;

        [Inject] private ITargetProvider targetProvider;
        private RaycastHit hitPoint => targetProvider.hitPoint;

        

        public override void Attack()
        {
            lastUsedTime = Time.time;
            AmmoCount--;

            PlayMuzzleFlash();
            if (hitPoint.transform != null) PlayBulletHitEffectParticle();
        }

        private void ShowBulletHole(Vector3 spawnPos)
        {
            GameObject bulletHit = Instantiate(BulletHole, spawnPos, Quaternion.LookRotation(hitPoint.normal));
            Destroy(bulletHit, 5f);
        }

        private void PlayBulletHitEffectParticle()
        {
            var damageable = hitPoint.transform.GetComponent<IDamageable>();
            if (damageable != null)
            {
                damageable.TakeDamage(10f);
            }

            Vector3 spawnPos = hitPoint.point + hitPoint.normal * 0.01f;

            BulletHitEffectParticle.transform.position = spawnPos;
            BulletHitEffectParticle.transform.rotation = Quaternion.LookRotation(hitPoint.normal);
            
            BulletHitEffectParticle.Play(true);
        }

        public override void Reload()
        {
            base.Reload();
            AmmoCount = 40;
        }

        private void PlayMuzzleFlash()
        {
            MuzzleFlashParticle.Play(true);
        }
    }
}
