using UnityEngine;
using UnityEngine.UI;
using TMPro;

/// <summary>
/// Attach to any manager GO in join lobby.unity.
/// Converts the "code" button GO into a working TMP_InputField at runtime
/// and wires the join button to call GameManager.JoinLobbyButton().
/// </summary>
public class JoinLobbyUI : MonoBehaviour
{
    private TMP_InputField _codeInput;
    private TMP_Text _errorText;

    void Start()
    {
        // ── Build proper code input from the "code" Button GO ─────────────────
        var codeGO = GameObject.Find("code");
        if (codeGO != null)
        {
            var rt = codeGO.GetComponent<RectTransform>();
            if (rt != null)
            {
                // Remove Button — it swallows click events before input field can act
                var btn = codeGO.GetComponent<Button>();
                if (btn != null) DestroyImmediate(btn);
                var oldField = codeGO.GetComponent<TMP_InputField>();
                if (oldField != null) DestroyImmediate(oldField);

                // Clear art-team child text labels
                var kill = new System.Collections.Generic.List<GameObject>();
                foreach (Transform child in rt) kill.Add(child.gameObject);
                foreach (var go in kill) DestroyImmediate(go);

                // Background
                var img = codeGO.GetComponent<Image>();
                if (img == null) img = codeGO.AddComponent<Image>();
                img.color = new Color(0.08f, 0.10f, 0.20f, 0.92f);

                // Viewport > Placeholder + Text
                var vpRT = MakeChild("Text Area", rt);
                vpRT.anchorMin = Vector2.zero;
                vpRT.anchorMax = Vector2.one;
                vpRT.offsetMin = new Vector2(18f, 6f);
                vpRT.offsetMax = new Vector2(-18f, -6f);
                vpRT.gameObject.AddComponent<RectMask2D>();

                var phRT = MakeChild("Placeholder", vpRT);
                Stretch(phRT);
                var ph = phRT.gameObject.AddComponent<TextMeshProUGUI>();
                ph.text      = "Enter lobby code...";
                ph.fontSize  = 48;
                ph.color     = new Color(0.55f, 0.60f, 0.70f, 0.85f);
                ph.fontStyle = FontStyles.Italic;
                ph.alignment = TextAlignmentOptions.Center;

                var txtRT = MakeChild("Text", vpRT);
                Stretch(txtRT);
                var txt = txtRT.gameObject.AddComponent<TextMeshProUGUI>();
                txt.text      = "";
                txt.fontSize  = 52;
                txt.color     = Color.white;
                txt.fontStyle = FontStyles.Bold;
                txt.alignment = TextAlignmentOptions.Center;
                txt.characterSpacing = 8f;

                _codeInput = codeGO.AddComponent<TMP_InputField>();
                _codeInput.textViewport          = vpRT;
                _codeInput.textComponent         = txt;
                _codeInput.placeholder           = ph;
                _codeInput.targetGraphic         = img;
                _codeInput.characterLimit        = 8;
                _codeInput.characterValidation   = TMP_InputField.CharacterValidation.Alphanumeric;
                _codeInput.keyboardType          = TouchScreenKeyboardType.Default;
                _codeInput.shouldHideMobileInput = false;
                // Auto-uppercase as user types
                _codeInput.onValueChanged.AddListener(v =>
                    _codeInput.SetTextWithoutNotify(v.ToUpperInvariant()));
            }
        }

        // ── Wire the join button ───────────────────────────────────────────────
        // Art team named the button "připojit" with literal quote marks in the name
        var joinBtnGO = FindGOByNameContains("ipojit");
        if (joinBtnGO != null)
        {
            var joinBtn = joinBtnGO.GetComponent<Button>();
            if (joinBtn == null) joinBtn = joinBtnGO.AddComponent<Button>();
            joinBtn.onClick.AddListener(OnJoinClicked);
        }

        // ── Error label (optional) ─────────────────────────────────────────────
        var errGO = GameObject.Find("error") ?? GameObject.Find("ErrorText");
        if (errGO != null)
        {
            _errorText = errGO.GetComponent<TMP_Text>();
            if (_errorText != null) _errorText.gameObject.SetActive(false);
        }
    }

    void OnJoinClicked()
    {
        var gm = GameManager.Instance;
        if (gm == null) return;

        string code = _codeInput != null ? _codeInput.text.Trim() : "";
        if (string.IsNullOrEmpty(code))
        {
            ShowError("Enter a lobby code!");
            return;
        }

        if (_errorText != null) _errorText.gameObject.SetActive(false);
        gm.JoinLobbyButton(code);
    }

    void ShowError(string msg)
    {
        if (_errorText == null) return;
        _errorText.text = msg;
        _errorText.gameObject.SetActive(true);
    }

    // Finds a GO whose name contains the substring (handles Art-team quoted names)
    GameObject FindGOByNameContains(string substring)
    {
        foreach (var go in FindObjectsOfType<GameObject>())
            if (go.name.Contains(substring)) return go;
        return null;
    }

    RectTransform MakeChild(string name, RectTransform parent)
    {
        var go = new GameObject(name);
        var rt = go.AddComponent<RectTransform>();
        rt.SetParent(parent, false);
        rt.localScale = Vector3.one;
        return rt;
    }

    void Stretch(RectTransform rt)
    {
        rt.anchorMin = Vector2.zero;
        rt.anchorMax = Vector2.one;
        rt.offsetMin = rt.offsetMax = Vector2.zero;
    }
}
