using UnityEngine;
using UnityEngine.InputSystem;

/// <summary>
/// Connects player input events to animation triggers.
/// Focused on the 8 core animations: Jab, Haymaker, BasicKick, SumoSlap, SpinningBackfist, ElbowSmash, AirPunch, LowKick
/// </summary>
public class InputToAnimation : MonoBehaviour
{
    private AnimationManager animManager;
    private PlayerInput playerInput;
    private WeaponManager weaponManager;
    [SerializeField] private PlayerScript playerScript; // for gating attacks/pause
    
    // TeamMember reference for control type checking
    private TeamMember _teamMember;

    [Header("Animation Triggers")]
    [SerializeField] private string jabInputAction = "Jab";
    [SerializeField] private string haymakerInputAction = "Haymaker";
    [SerializeField] private string spinningBackfistInputAction = "SpinningBackfist";
    [SerializeField] private string elbowSmashInputAction = "ElbowSmash";
    [SerializeField] private string airPunchInputAction = "AirPunch";
    [SerializeField] private string lowKickInputAction = "LowKick";
    [SerializeField] private string basicKickInputAction = "BasicKick";
    [SerializeField] private string sumoSlapInputAction = "SumoSlap";
    [SerializeField] private string genericAttackInputAction = "Attack"; // Fallback single attack action

    private void Awake()
    {
        animManager = GetComponent<AnimationManager>();
        playerInput = GetComponent<PlayerInput>();
        weaponManager = GetComponent<WeaponManager>();
        _teamMember = GetComponent<TeamMember>();
        
        if (playerScript == null)
        {
            playerScript = GetComponent<PlayerScript>();
        }

        if (animManager == null)
        {
            animManager = gameObject.AddComponent<AnimationManager>();
            Debug.Log("Added AnimationManager component automatically");
        }

        if (playerInput == null)
        {
            Debug.LogError("PlayerInput component is required on this GameObject");
        }
    }

    private void OnEnable()
    {
        if (playerInput != null)
        {
            // Connect action events
            SetupInputCallbacks();
        }
    }

    private void OnDisable()
    {
        // Cleanup if needed
    }

    /// <summary>
    /// Sets up the callbacks from input actions to animations
    /// </summary>
    private void SetupInputCallbacks()
    {
        // Register callbacks for our 8 core animations
        RegisterActionCallback(jabInputAction, AnimationNames.Jab);
        RegisterActionCallback(haymakerInputAction, AnimationNames.Haymaker);
        RegisterActionCallback(spinningBackfistInputAction, AnimationNames.SpinningBackfist);
        RegisterActionCallback(elbowSmashInputAction, AnimationNames.ElbowSmash);
        RegisterActionCallback(airPunchInputAction, AnimationNames.AirPunch);
        RegisterActionCallback(lowKickInputAction, AnimationNames.LowKick);
        RegisterActionCallback(basicKickInputAction, AnimationNames.BasicKick);
        RegisterActionCallback(sumoSlapInputAction, AnimationNames.SumoSlap);
        
        // Also support a single generic "Attack" action by mapping it to a default attack (Jab)
        RegisterActionCallback(genericAttackInputAction, AnimationNames.Jab);
        
        // Basic fallbacks for common inputs
        RegisterActionCallback("Punch", AnimationNames.Jab);
        RegisterActionCallback("Kick", AnimationNames.LowKick);
        RegisterActionCallback("Strike", AnimationNames.Haymaker);
    }

    /// <summary>
    /// Registers a callback for an input action to trigger an animation
    /// </summary>
    private void RegisterActionCallback(string actionName, string animationName)
    {
        if (playerInput == null) return;

        // Use throwIfNotFound=false to gracefully handle missing actions
        InputAction action = playerInput.actions.FindAction(actionName, false);
        
        if (action != null)
        {
            action.performed += ctx => PlayAnimation(animationName);
        }
        // Silently ignore missing actions - not all input assets have all actions
    }
    
    /// <summary>
    /// Plays an animation using the AnimationManager, allowing weapon overrides
    /// </summary>
    private void PlayAnimation(string animationName)
    {
        if (animManager == null) return;
        
        // CRITICAL FIX: Only respond to input if this character is HumanControlled
        // This prevents AI teammates from triggering attacks when the player presses buttons
        if (_teamMember != null && _teamMember.CurrentControlType != TeamMember.ControlType.HumanControlled)
        {
            return;
        }
        
        // Also check if PlayerInput is enabled (double safety)
        if (playerInput != null && !playerInput.enabled)
        {
            return;
        }

        // Respect PlayerScript gameplay state to prevent duplicate/invalid triggers
        if (playerScript != null)
        {
            // Only allow when attacks are enabled and player isn't blocking or dodging
            if (!playerScript.attack || playerScript.block || playerScript.dodge)
                return;
        }

        // If a weapon is equipped, resolve to the weapon's animation set
        if (weaponManager != null && weaponManager.IsWeaponEquipped)
        {
            animationName = weaponManager.ResolveAnimation(animationName);
        }

        animManager.PlayAnimation(animationName);
    }
    
    // Public method to manually trigger animations from other scripts
    public void TriggerAnimation(string animationName)
    {
        PlayAnimation(animationName);
    }
}