using Cirno.Scripts.Components.FSM;
using Cirno.Scripts.Interactables;
using Godot;

namespace Cirno.Scripts.Components.Actors;

public partial class ActivationProvider : Area2D
{
    public bool Enabled { get; set; } = false;
    
    private Selector _selector;
    
    [Export]
    public PackedScene SelectorScene { get; set; }
    
    [Export]
    private InputProvider _inputProvider;

    [Export] private AudioStreamPlayer2D _errorSound;
    
    //[Signal]
    //public delegate void InteractableAreaEnteredEventHandler(Interactable interactable);
    
    //[Signal]
    //public delegate void InteractableAreaExitedEventHandler(Interactable interactable);

    public void Init(CharacterBody2D actor)
    {
        if (SelectorScene is not null && _selector is null)
        {
            _selector = actor.CreateSibling<Selector>(SelectorScene, this.GlobalPosition);
            _selector.Visible = false;
        }
    }
    
    public void HandleInteraction()
    {
        if (_inputProvider.GetUseJustPressed())
        {
            if (!TrySelect())
            {
                _selector.SelectNext();
            }

            return;
        }

        if (_inputProvider.GetScanJustPressed())
        {
            _selector.SelectNext();
        }
    }

    private bool TrySelect()
    {
        var selected = _selector.SelectedInteractable;
        if (selected is null)
        {
            _errorSound?.Play();
            return false;
        };
        if (!selected.CanActivate())
        {
            _errorSound?.Play();
            return true;
        };
        bool success = selected.Activate(ActivationType.Use);

        if (success)
        {
            // Deselect and scan for next
            _selector.SelectNext();
            //_selector.RemoveInteractable(selected);
        }
        else
        {
            _errorSound?.Play();
        }

        return true;
        //var spaceState = GetWorld2D().DirectSpaceState;

        //var query = PhysicsRayQueryParameters2D.Create(Vector2.Zero, )
    }
    
    private void _on_interaction_controller_area_entered(Area2D area)
    {
        if (!Enabled) return;
        if (area.IsInGroup("Interactable") && area is IInteractable interactable && interactable.CanActivate())
        {
            //EmitSignal(nameof(InteractableAreaEntered), interactable);

            if (_selector == null) return;

            _selector.AddInteractable(interactable);
        }
    }
    
    private void _on_interaction_controller_area_exited(Area2D area)
    {
        //if (!Enabled) return;
        if (area.IsInGroup("Interactable") && area is IInteractable interactable)
        {
            //EmitSignal(nameof(InteractableAreaExited), interactable);

            if (_selector == null) return;
            _selector.RemoveInteractable(interactable);
        }
    }
}