using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using System.Collections.Generic;

namespace Northbound
{
    /// <summary>
    /// 상호작용 대상 없이 실행 가능한 액션들을 관리
    /// </summary>
    public class PlayerActionSystem : NetworkBehaviour
    {
        [Header("Actions")]
        public List<MonoBehaviour> actionComponents = new List<MonoBehaviour>();

        [Header("Animation")]
        public bool playAnimations = true;

        private PlayerInputActions _inputActions;
        private Dictionary<string, IAction> _actions = new Dictionary<string, IAction>();
        private Animator _animator;

        private void Awake()
        {
            _animator = GetComponent<Animator>();
        }

        public override void OnNetworkSpawn()
        {
            if (!IsOwner) return;

            // 액션 컴포넌트들을 딕셔너리에 등록
            foreach (var component in actionComponents)
            {
                if (component is IAction action)
                {
                    _actions[action.GetActionName()] = action;
                }
            }

            _inputActions = new PlayerInputActions();
            _inputActions.Player.Attack.performed += OnAttack;
            // 다른 액션들도 여기에 바인딩
            _inputActions.Enable();
        }

        public override void OnNetworkDespawn()
        {
            if (IsOwner && _inputActions != null)
            {
                _inputActions.Player.Attack.performed -= OnAttack;
                _inputActions.Disable();
                _inputActions.Dispose();
            }
        }

        private void OnAttack(InputAction.CallbackContext context)
        {
            ExecuteAction("Attack");
        }

        public void ExecuteAction(string actionName)
        {
            if (_actions.TryGetValue(actionName, out IAction action))
            {
                if (action.CanExecute(OwnerClientId))
                {
                    // 애니메이션 재생 (액션 실행 전)
                    if (playAnimations && _animator != null)
                    {
                        string animTrigger = action.GetActionAnimation();
                        if (!string.IsNullOrEmpty(animTrigger))
                        {
                            _animator.SetTrigger(animTrigger);
                        }
                    }

                    action.Execute(OwnerClientId);
                }
            }
        }

        private void OnDestroy()
        {
            if (_inputActions != null)
            {
                _inputActions.Dispose();
            }
        }
    }
}