using UnityEngine;
using UnityEngine.InputSystem;
using System;

public class InputManager : MonoBehaviour
{
    public static InputManager Instance { get; private set; }
    private PlayerInput playerInput;
    private InputAction touchPressAction;
    private InputAction touchPositionAction;
    private ITouchInputConsumer defaultConsumer;

    void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
        playerInput = GetComponent<PlayerInput>();
        if (playerInput == null)
        {
            Debug.LogError("InputManager requires a PlayerInput component attached to the same GameObject.");
            return;
        }
        // Find actions by name in the assigned action map
        touchPressAction = playerInput.actions.FindAction("TouchPress", false);
        touchPositionAction = playerInput.actions.FindAction("TouchPosition", false);
    }

    void OnEnable()
    {
        if (touchPressAction != null)
            touchPressAction.performed += OnTouchPressPerformed;
        if (touchPositionAction != null)
            touchPositionAction.performed += OnTouchPositionPerformed;
    }

    void OnDisable()
    {
        if (touchPressAction != null)
            touchPressAction.performed -= OnTouchPressPerformed;
        if (touchPositionAction != null)
            touchPositionAction.performed -= OnTouchPositionPerformed;
    }

    public void SetDefaultConsumer(ITouchInputConsumer consumer)
    {
        defaultConsumer = consumer;
    }

    private void OnTouchPressPerformed(InputAction.CallbackContext ctx)
    {
        // For button actions, you may want to use InputValue or just handle the event
        // If you need position, you can read it from touchPositionAction
        Vector3 _screenPos = Camera.main.ScreenToWorldPoint(touchPositionAction.ReadValue<Vector2>());
        Vector2 screenPos = new Vector2(_screenPos.x, _screenPos.y);
        if (!TryDelegateToInteractable(screenPos))
            defaultConsumer?.OnTouchPress(screenPos);
    }

    private void OnTouchPositionPerformed(InputAction.CallbackContext ctx)
    {
        Vector2 pos = ctx.ReadValue<Vector2>();
        defaultConsumer?.OnTouchPosition(pos);
    }

    private bool TryDelegateToInteractable(Vector2 worldPos)
    {
        // Raycast at the world position to find an Interactable
        Collider2D hit = Physics2D.OverlapPoint(worldPos);
        if (hit != null)
        {
            var interactable = hit.GetComponent<Interactable>();
            if (interactable != null)
            {
                interactable.OnTouchPress(worldPos);
                return true;
            }
        }
        return false;
    }
}
