using UdonSharp;
using UnityEngine;
using UnityEngine.UI;
using VRC.SDKBase;

// Optional in-world HUD. Wire the public On... methods to Unity UI Buttons in
// the inspector; UdonSharp does not support Button.onClick.AddListener.
public class ZeroInventoryHud : UdonSharpBehaviour
{
    [Header("References")]
    public ZeroInventoryClient client;
    public Text statusText;
    public Text inventoryText;
    public Text feedbackText;

    [Header("People list")]
    public GameObject playerListPanel;
    public Text playerHeaderText;
    public Text[] playerRows;
    public bool playersExpanded = true;

    [Header("Panel")]
    public GameObject panel;
    public KeyCode toggleKey = KeyCode.I;
    public bool desktopOnly = true;
    public float panelDistance = 1.2f;
    public float panelHeightOffset = -0.12f;

    private float nextRefresh = 0f;

    void Start()
    {
        // The panel starts closed; on desktop the player opens it with the
        // toggle key. Udon runs this per client, so it is a local view.
        SetPanelVisible(false);
        if (playerListPanel != null) playerListPanel.SetActive(playersExpanded);
    }

    void Update()
    {
        HandlePanelToggle();

        if (client == null) return;
        if (Time.time < nextRefresh) return;
        nextRefresh = Time.time + 0.25f;

        if (statusText != null) statusText.text = client.StatusLine();

        if (feedbackText != null)
        {
            if (client.lastError != "") feedbackText.text = client.lastError;
            else if (client.loading) feedbackText.text = "Loading...";
            else feedbackText.text = client.statusMessage;
        }

        if (inventoryText != null) inventoryText.text = client.inventoryText;

        if (playerHeaderText != null)
        {
            string arrow = playersExpanded ? "  v" : "  >";
            playerHeaderText.text = "People (" + client.IntToString(client.playerCount) + ")" + arrow;
        }
        ApplyPlayerRows();
    }

    // ---------- people list ----------

    // The rows exist in the scene because Udon cannot create UI at runtime; the
    // header folds the whole list away when the panel is crowded.
    private void ApplyPlayerRows()
    {
        if (playerRows == null) return;
        int count = client.playerCount;
        for (int index = 0; index < playerRows.Length; index++)
        {
            Text row = playerRows[index];
            if (row == null) continue;
            bool used =
                index < count && client.playerNames != null && index < client.playerNames.Length;
            row.text = used ? client.playerNames[index] : "";
            if (row.gameObject.activeSelf != used) row.gameObject.SetActive(used);
        }
    }

    public void OnPlayersToggled()
    {
        playersExpanded = !playersExpanded;
        if (playerListPanel != null) playerListPanel.SetActive(playersExpanded);
    }

    // ---------- panel ----------

    private void HandlePanelToggle()
    {
        if (panel == null) return;

        VRCPlayerApi local = Networking.LocalPlayer;
        bool inVR = local != null && local.IsUserInVR();

        // Desktop only for now: VR players never get the panel.
        if (desktopOnly && inVR)
        {
            if (panel.activeSelf) SetPanelVisible(false);
            return;
        }

        if (Input.GetKeyDown(toggleKey))
        {
            if (panel.activeSelf) SetPanelVisible(false);
            else ShowPanelInFront();
        }
    }

    // Puts the panel in front of the local player's head every time it opens, so
    // it is readable wherever they are standing.
    private void ShowPanelInFront()
    {
        VRCPlayerApi local = Networking.LocalPlayer;
        if (local != null)
        {
            VRCPlayerApi.TrackingData head =
                local.GetTrackingData(VRCPlayerApi.TrackingDataType.Head);

            Vector3 forward = head.rotation * Vector3.forward;
            forward.y = 0f;
            if (forward.sqrMagnitude < 0.0001f) forward = Vector3.forward;
            forward = forward.normalized;

            Transform panelTransform = panel.transform;
            // A world space canvas reads from its local -Z side, so +Z has to
            // point away from the player for the text to face them.
            panelTransform.rotation = Quaternion.LookRotation(forward, Vector3.up);
            panelTransform.position =
                head.position + forward * panelDistance + Vector3.up * panelHeightOffset;
        }

        SetPanelVisible(true);
    }

    private void SetPanelVisible(bool visible)
    {
        if (panel == null) return;
        if (panel.activeSelf != visible) panel.SetActive(visible);
    }

    // ---------- buttons ----------

    public void OnConnectClicked()
    {
        if (client == null) return;
        client.ConnectFromInput();
    }

    public void OnNextCharacterClicked()
    {
        if (client == null) return;
        client.NextCharacter();
    }

    public void OnPreviousCharacterClicked()
    {
        if (client == null) return;
        client.PreviousCharacter();
    }

    public void OnRefreshClicked()
    {
        if (client == null) return;
        client.RefreshNow();
    }

    public void OnDisconnectClicked()
    {
        if (client == null) return;
        client.Disconnect();
    }
}
