using UnityEngine;

public class InteractableObject : MonoBehaviour
{
    [SerializeField] private string objectId;
    [SerializeField] private string objectType = "arcade_cabinet";

    [Header("Visual Feedback")]
    [SerializeField] private GameObject highlightEffect;
    [SerializeField] private Renderer[] renderers;

    private string _currentState = "default";

    public string ObjectId => objectId;
    public string CurrentState => _currentState;

    private void Start()
    {
        if (string.IsNullOrEmpty(objectId))
            objectId = gameObject.name;

        if (ArcadeNetworkManager.Instance != null)
            ArcadeNetworkManager.Instance.OnObjectStateChanged += OnNetworkStateChanged;
    }

    private void OnDestroy()
    {
        if (ArcadeNetworkManager.Instance != null)
            ArcadeNetworkManager.Instance.OnObjectStateChanged -= OnNetworkStateChanged;
    }

    public void Interact()
    {
        if (ArcadeNetworkManager.Instance == null || !ArcadeNetworkManager.Instance.IsConnected)
            return;

        ArcadeNetworkManager.Instance.SendInteract(objectId);
    }

    public void Release()
    {
        if (ArcadeNetworkManager.Instance == null || !ArcadeNetworkManager.Instance.IsConnected)
            return;

        ArcadeNetworkManager.Instance.SendRelease(objectId);
    }

    public void SetHighlight(bool active)
    {
        if (highlightEffect != null)
            highlightEffect.SetActive(active);
    }

    private void OnNetworkStateChanged(string changedObjectId, NetworkWorldObject worldObject)
    {
        if (changedObjectId != objectId) return;

        string prevState = _currentState;
        _currentState = worldObject.state;

        OnStateChanged(prevState, _currentState, worldObject.usedBy);
    }

    protected virtual void OnStateChanged(string from, string to, string usedBy)
    {
        switch (objectType)
        {
            case "door":
                HandleDoorState(to);
                break;
            case "arcade_cabinet":
                HandleCabinetState(to, usedBy);
                break;
            case "toggle":
                HandleToggleState(to);
                break;
        }
    }

    private void HandleDoorState(string state)
    {
        var animator = GetComponent<Animator>();
        if (animator != null)
            animator.SetBool("IsOpen", state == "open");
    }

    private void HandleCabinetState(string state, string usedBy)
    {
        bool inUse = state == "in_use";
        bool isMe = usedBy == ArcadeNetworkManager.Instance?.SessionId;

        if (inUse && isMe)
        {
            Debug.Log($"[Interact] You're using {objectId}!");
        }
    }

    private void HandleToggleState(string state)
    {
        var animator = GetComponent<Animator>();
        if (animator != null)
            animator.SetBool("IsOn", state == "on");
    }
}
