using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace GameSDK
{
    /// <summary>
    /// 登录面板（miHoYo风格布局）
    /// 支持[ExecuteInEditMode]，在编辑器模式下也能预览布局效果
    /// </summary>
    [ExecuteInEditMode]
    public class LoginPanel : BasePanel
    {
        [Header("UI References")]
        public TMP_InputField usernameInput;
        public TMP_InputField passwordInput;
        public Button loginBtn;
        public Button registerBtn;
        public Button changePasswordBtn;
        public Button guestLoginBtn;
        public TMP_Text tipText;

        // 运行时创建的UI元素引用
        private GameObject subtitleObj;       // 副标题 "TECH OTAKUS SAVE THE WORLD"
        private GameObject closeBtnObj;       // 关闭按钮 X
        private GameObject agreementRowObj;   // 协议勾选行

        private bool initialized;

#if UNITY_EDITOR
        private int lastLayoutVersion = 0;
#endif

        protected override void Awake()
        {
            base.Awake();
            InitLayout();
            // 仅在运行模式下绑定按钮事件（编辑模式不需要）
            if (Application.isPlaying)
                BindButtons();
        }

#if UNITY_EDITOR
        /// <summary>
        /// 编辑器模式下，脚本加载、Inspector值变化、对象选中时都会触发
        /// 确保在Scene视图中也能看到正确布局
        /// </summary>
        private void OnValidate()
        {
            // 避免在非播放模式且对象未激活时执行（Awake不会触发的情况）
            if (!Application.isPlaying && gameObject.activeInHierarchy)
            {
                // 延迟一帧执行，确保所有序列化字段已就绪
                UnityEditor.EditorApplication.delayCall += () =>
                {
                    if (this != null && gameObject != null)
                        InitLayout();
                };
            }
        }

        /// <summary>
        /// 右键菜单：手动刷新布局
        /// </summary>
        [UnityEditor.MenuItem("CONTEXT/LoginPanel/刷新布局")]
        private static void RefreshLayout(UnityEditor.MenuCommand command)
        {
            var panel = (LoginPanel)command.context;
            if (panel != null)
            {
                panel.initialized = false; // 强制重新初始化
                panel.InitLayout();
                UnityEditor.EditorUtility.SetDirty(panel);
            }
        }
#endif

        /// <summary>
        /// 初始化miHoYo风格布局（每次Awake调用，确保Play模式下修改也生效）
        /// </summary>
        private void InitLayout()
        {
            var card = transform.Find("Card");
            if (card == null)
            {
                Debug.LogError("[LoginPanel] Card not found!");
                return;
            }

            var cardRt = card.GetComponent<RectTransform>();

            // === 1. 标题: miHoYo + 副标题 ===
            SetupTitle(card);

            // === 2. 输入框：去掉标签，更新placeholder ===
            SetupInputFields(card);

            // === 3. 按钮文字与样式 ===
            SetupButtons(card);

            // === 4. 隐藏游客登录按钮 ===
            var guestBtn = card.Find("游客登录Btn");
            if (guestBtn != null) guestBtn.gameObject.SetActive(false);

            // === 5. 提示文字位置 ===
            var tip = card.Find("TipText");
            if (tip != null)
            {
                var tipRt = tip.GetComponent<RectTransform>();
                tipRt.anchorMin = new Vector2(0.5f, 0.5f);
                tipRt.anchorMax = new Vector2(0.5f, 0.5f);
                tipRt.pivot = new Vector2(0.5f, 0.5f);
                tipRt.sizeDelta = new Vector2(300f, 30f);
                tipRt.anchoredPosition = new Vector2(0f, -175f);
            }

            // === 6. 创建协议勾选行 ===
            SetupAgreementRow(card);

            // === 7. 创建关闭按钮(X) ===
            SetupCloseButton(card);
        }

        #region 布局子方法

        private void SetupTitle(Transform card)
        {
            var titleTf = card.Find("Title");
            if (titleTf == null) return;

            var titleRt = titleTf.GetComponent<RectTransform>();
            titleRt.anchorMin = new Vector2(0.5f, 0.5f);
            titleRt.anchorMax = new Vector2(0.5f, 0.5f);
            titleRt.pivot = new Vector2(0.5f, 0.5f);
            titleRt.sizeDelta = new Vector2(380f, 50f);
            titleRt.anchoredPosition = new Vector2(0f, 220f);

            var titleTxt = titleTf.GetComponent<TMP_Text>();
            if (titleTxt != null)
            {
                titleTxt.text = "miHoYo";
                titleTxt.fontSize = 28f;
                titleTxt.fontStyle = FontStyles.Bold;
                titleTxt.alignment = TextAlignmentOptions.Center;
            }

            // 副标题
            subtitleObj = EnsureChild(card, "Subtitle", "Title");
            if (subtitleObj != null)
            {
                var subRt = subtitleObj.GetComponent<RectTransform>();
                ResetRectTransform(subRt,
                    new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f),
                    new Vector2(0.5f, 0.5f), new Vector2(380f, 20f),
                    new Vector2(0f, 185f));

                var subTxt = subtitleObj.GetComponent<TextMeshProUGUI>();
                if (subTxt == null)
                {
                    subTxt = subtitleObj.AddComponent<TextMeshProUGUI>();
                    subTxt.font = GetFont(card);
                }
                subTxt.text = "TECH OTAKUS SAVE THE WORLD";
                subTxt.fontSize = 10f;
                subTxt.color = new Color(0.6f, 0.6f, 0.6f);
                subTxt.alignment = TextAlignmentOptions.Center;
            }
        }

        private void SetupInputFields(Transform card)
        {
            string accKey = "账号Group";
            string pwdKey = "密码Group";

            // 账号输入框
            var accGroup = card.Find(accKey);
            if (accGroup != null)
            {
                // 隐藏标签
                var label = accGroup.Find("Label");
                if (label != null) label.gameObject.SetActive(false);

                // 调整Group和InputField尺寸
                var grpRt = accGroup.GetComponent<RectTransform>();
                grpRt.anchorMin = new Vector2(0.5f, 0.5f);
                grpRt.anchorMax = new Vector2(0.5f, 0.5f);
                grpRt.pivot = new Vector2(0.5f, 0.5f);
                grpRt.sizeDelta = new Vector2(380f, 55f);
                grpRt.anchoredPosition = new Vector2(0f, 125f);

                var inputField = accGroup.Find("InputField");
                if (inputField != null)
                {
                    var inputRt = inputField.GetComponent<RectTransform>();
                    inputRt.sizeDelta = new Vector2(360f, 50f);
                    inputRt.anchoredPosition = Vector2.zero;

                    var placeholder = inputField.Find("Placeholder")?.GetComponent<TMP_Text>();
                    if (placeholder != null) placeholder.text = "输入手机号/邮箱";

                    var inputImg = inputField.GetComponent<Image>();
                    if (inputImg != null) inputImg.color = new Color(0.95f, 0.96f, 0.97f, 1f);
                }
            }

            // 密码输入框
            var pwdGroup = card.Find(pwdKey);
            if (pwdGroup != null)
            {
                var label = pwdGroup.Find("Label");
                if (label != null) label.gameObject.SetActive(false);

                var grpRt = pwdGroup.GetComponent<RectTransform>();
                grpRt.anchorMin = new Vector2(0.5f, 0.5f);
                grpRt.anchorMax = new Vector2(0.5f, 0.5f);
                grpRt.pivot = new Vector2(0.5f, 0.5f);
                grpRt.sizeDelta = new Vector2(380f, 55f);
                grpRt.anchoredPosition = new Vector2(0f, 60f);

                var inputField = pwdGroup.Find("InputField");
                if (inputField != null)
                {
                    var inputRt = inputField.GetComponent<RectTransform>();
                    inputRt.sizeDelta = new Vector2(360f, 50f);
                    inputRt.anchoredPosition = Vector2.zero;

                    var placeholder = inputField.Find("Placeholder")?.GetComponent<TMP_Text>();
                    if (placeholder != null) placeholder.text = "输入密码";

                    var inputImg = inputField.GetComponent<Image>();
                    if (inputImg != null) inputImg.color = new Color(0.95f, 0.96f, 0.97f, 1f);
                }
            }
        }

        private void SetupButtons(Transform card)
        {
            // 登录按钮 -> 进入游戏（放在输入框下方）
            var loginBtnTf = card.Find("登录Btn");
            if (loginBtnTf != null)
            {
                var btnRt = loginBtnTf.GetComponent<RectTransform>();
                btnRt.sizeDelta = new Vector2(380f, 50f);
                btnRt.anchoredPosition = new Vector2(0f, 0f);

                var btnImg = loginBtnTf.GetComponent<Image>();
                if (btnImg != null) btnImg.color = new Color(0.18f, 0.22f, 0.28f); // 深灰底色

                var loginTxt = loginBtnTf.Find("Text")?.GetComponent<TMP_Text>();
                if (loginTxt != null)
                {
                    loginTxt.text = "进入游戏";
                    loginTxt.fontSize = 20f;
                    loginTxt.fontStyle = FontStyles.Bold;
                    loginTxt.color = Color.white;
                }
            }

            // 注册按钮 -> 没有账号？立即注册 (橙色文字链接)
            var regBtnTf = card.Find("注册账号Btn");
            if (regBtnTf != null)
            {
                var regRt = regBtnTf.GetComponent<RectTransform>();
                regRt.sizeDelta = new Vector2(180f, 36f);
                regRt.anchoredPosition = new Vector2(-90f, -55f);

                var regImg = regBtnTf.GetComponent<Image>();
                if (regImg != null) regImg.enabled = false; // 无背景

                var regTxt = regBtnTf.Find("Text")?.GetComponent<TMP_Text>();
                if (regTxt != null)
                {
                    regTxt.text = "没有账号？立即注册";
                    regTxt.fontSize = 14f;
                    regTxt.color = new Color(1f, 0.75f, 0f); // 橙色
                }
            }

            // 修改密码按钮 -> 忘记密码 (灰色文字链接)
            var pwdBtnTf = card.Find("修改密码Btn");
            if (pwdBtnTf != null)
            {
                var pwdRt = pwdBtnTf.GetComponent<RectTransform>();
                pwdRt.sizeDelta = new Vector2(100f, 36f);
                pwdRt.anchoredPosition = new Vector2(130f, -55f);

                var pwdImg = pwdBtnTf.GetComponent<Image>();
                if (pwdImg != null) pwdImg.enabled = false; // 无背景

                var pwdTxt = pwdBtnTf.Find("Text")?.GetComponent<TMP_Text>();
                if (pwdTxt != null)
                {
                    pwdTxt.text = "忘记密码";
                    pwdTxt.fontSize = 14f;
                    pwdTxt.color = new Color(0.55f, 0.45f, 0.35f); // 灰棕色
                }
            }
        }

        private void SetupAgreementRow(Transform card)
        {
            agreementRowObj = EnsureChild(card, "AgreementRow", "TipText");
            if (agreementRowObj == null) return;

            var rowRt = agreementRowObj.GetComponent<RectTransform>();
            rowRt.anchorMin = new Vector2(0.5f, 0.5f);
            rowRt.anchorMax = new Vector2(0.5f, 0.5f);
            rowRt.pivot = new Vector2(0.5f, 0.5f);
            rowRt.sizeDelta = new Vector2(380f, 30f);
            rowRt.anchoredPosition = new Vector2(200f, -95f);

            // === Toggle复选框 ===
            var toggleGo = EnsureChild(agreementRowObj.transform, "Toggle", null);
            var trt = toggleGo.GetComponent<RectTransform>();
            ResetRectTransform(trt, new Vector2(0f, 0.5f), new Vector2(0f, 0.5f),
                new Vector2(0f, 0.5f), new Vector2(20f, 20f), new Vector2(-190f, 0f));

            var tgl = toggleGo.GetComponent<Toggle>();
            if (tgl == null) tgl = toggleGo.AddComponent<Toggle>();
            tgl.isOn = true;

            var bgImg = toggleGo.GetComponent<Image>();
            if (bgImg == null) bgImg = toggleGo.AddComponent<Image>();
            bgImg.color = new Color(0.9f, 0.9f, 0.9f);

            // Checkmark（仅在不存在时创建）
            if (toggleGo.transform.Find("Checkmark") == null)
            {
                var chk = new GameObject("Checkmark");
                chk.transform.SetParent(toggleGo.transform, false);
                var crt = chk.AddComponent<RectTransform>();
                crt.anchorMin = Vector2.zero;
                crt.anchorMax = Vector2.zero;
                crt.sizeDelta = new Vector2(18f, 18f);
                crt.anchoredPosition = Vector2.zero;
                crt.pivot = new Vector2(0.5f, 0.5f);
                var cki = chk.AddComponent<Image>();
                cki.color = new Color(0.15f, 0.55f, 1f); // 蓝色勾
                tgl.graphic = cki;
            }

            // === 协议文本 ===
            var txtGo = EnsureChild(agreementRowObj.transform, "AgreeText", "Toggle");
            var txtRt = txtGo.GetComponent<RectTransform>();
            ResetRectTransform(txtRt, new Vector2(0f, 0.5f), new Vector2(1f, 0.5f),
                new Vector2(0.5f, 0.5f), new Vector2(340f, 25f), new Vector2(10f, 0f));

            var agreeTxt = txtGo.GetComponent<TextMeshProUGUI>();
            if (agreeTxt == null)
            {
                agreeTxt = txtGo.AddComponent<TextMeshProUGUI>();
                agreeTxt.font = GetFont(card);
            }
            agreeTxt.text = "已同意《用户协议》和《隐私政策》";
            agreeTxt.fontSize = 13f;
            agreeTxt.color = new Color(0.65f, 0.65f, 0.65f);
            agreeTxt.alignment = TextAlignmentOptions.Left;
        }

        private void SetupCloseButton(Transform card)
        {
            closeBtnObj = EnsureChild(card, "CloseBtn", null, insertAtFront: true);
            if (closeBtnObj == null) return;

            var cRt = closeBtnObj.GetComponent<RectTransform>();
            ResetRectTransform(cRt, new Vector2(1f, 1f), new Vector2(1f, 1f),
                new Vector2(0.5f, 0.5f), new Vector2(30f, 30f), new Vector2(-20f, -20f));

            if (closeBtnObj.GetComponent<Button>() == null)
                closeBtnObj.AddComponent<Button>().onClick.AddListener(() => Debug.Log("[LoginPanel] 关闭"));

            var cImg = closeBtnObj.GetComponent<Image>();
            if (cImg == null) cImg = closeBtnObj.AddComponent<Image>();
            cImg.color = new Color(0.3f, 0.3f, 0.3f);

            // X 文字（始终重置位置）
            var xTf = EnsureChild(closeBtnObj.transform, "XText", null);
            var xRt = xTf.GetComponent<RectTransform>();
            ResetRectTransform(xRt, Vector2.zero, Vector2.zero,
                new Vector2(0.5f, 0.5f), new Vector2(30f, 30f), Vector2.zero);

            var xtxt = xTf.GetComponent<TextMeshProUGUI>();
            if (xtxt == null)
            {
                xtxt = xTf.AddComponent<TextMeshProUGUI>();
                xtxt.font = GetFont(card);
            }
            xtxt.text = "\u00D7"; // × 符号
            xtxt.fontSize = 18f;
            xtxt.color = Color.white;
            xtxt.alignment = TextAlignmentOptions.Center;
        }

        #endregion

        #region 工具方法

        /// <summary>确保子对象存在，不存在则创建。insertAfterName指定在哪个兄弟之后插入</summary>
        private GameObject EnsureChild(Transform parent, string name, string insertAfterName = null, bool insertAtFront = false)
        {
            var existing = parent.Find(name)?.gameObject;
            if (existing != null) return existing;

            var go = new GameObject(name);
            go.transform.SetParent(parent, false);
            go.AddComponent<RectTransform>(); // 确保有RT组件

            // 设置插入位置
            if (insertAtFront)
                go.transform.SetAsFirstSibling();
            else if (!string.IsNullOrEmpty(insertAfterName))
            {
                var afterTf = parent.Find(insertAfterName);
                if (afterTf != null)
                    go.transform.SetSiblingIndex(afterTf.GetSiblingIndex() + 1);
            }

            return go;
        }

        /// <summary>完全重置RectTransform的所有属性（解决编辑模式下新建对象RT默认值异常的问题）</summary>
        private static void ResetRectTransform(RectTransform rt, Vector2 anchorMin, Vector2 anchorMax,
            Vector2 pivot, Vector2 sizeDelta, Vector2 anchoredPosition)
        {
            rt.anchorMin = anchorMin;
            rt.anchorMax = anchorMax;
            rt.pivot = pivot;
            rt.sizeDelta = sizeDelta;
            rt.anchoredPosition = anchoredPosition;
            // 注意：不要设offsetMin/offsetMax，它们会覆盖上面设置的sizeDelta和anchoredPosition
        }

        private TMP_FontAsset GetFont(Transform card)
        {
            var titleTxt = card.Find("Title")?.GetComponent<TMP_Text>();
            if (titleTxt != null && titleTxt.font != null)
                return titleTxt.font;
            // fallback: 从全局资源找SimHei_SDF
            var font = Resources.Load<TMP_FontAsset>("Fonts/SimHei_SDF");
            if (font != null) return font;
            return null;
        }

        private void BindButtons()
        {
            if (initialized) return;
            initialized = true;
            if (loginBtn != null) loginBtn.onClick.AddListener(OnLoginClick);
            if (registerBtn != null) registerBtn.onClick.AddListener(OnRegisterClick);
            if (changePasswordBtn != null) changePasswordBtn.onClick.AddListener(OnChangePasswordClick);
            if (guestLoginBtn != null) guestLoginBtn.onClick.AddListener(OnGuestLoginClick);
        }

        private void UnbindButtons()
        {
            if (!initialized) return;
            initialized = false;
            if (loginBtn != null) loginBtn.onClick.RemoveListener(OnLoginClick);
            if (registerBtn != null) registerBtn.onClick.RemoveListener(OnRegisterClick);
            if (changePasswordBtn != null) changePasswordBtn.onClick.RemoveListener(OnChangePasswordClick);
            if (guestLoginBtn != null) guestLoginBtn.onClick.RemoveListener(OnGuestLoginClick);
        }

        private void OnDisable()
        {
            UnbindButtons();
        }

        private void OnDestroy()
        {
            UnbindButtons();
        }

        #endregion

        private void OnLoginClick()
        {
            string username = usernameInput.text.Trim();
            string password = passwordInput.text.Trim();

            if (string.IsNullOrEmpty(username))
            {
                ShowTip("请输入账号");
                return;
            }
            if (string.IsNullOrEmpty(password))
            {
                ShowTip("请输入密码");
                return;
            }

            // TODO: 接入实际登录接口
            Debug.Log($"[SDK] 登录请求: 账号={username}, 密码={password}");
            ShowTip("登录中...");

            // 模拟登录成功
            SDKManager.Instance.LoginSuccess(username);
            SDKUIManager.Instance.PopPanel();
            SDKUIManager.Instance.ShowPanel<RealNameAuthPanel>();
        }

        private void OnRegisterClick()
        {
            SDKUIManager.Instance.ShowPanel<RegisterPanel>();
        }

        private void OnChangePasswordClick()
        {
            SDKUIManager.Instance.ShowPanel<ChangePasswordPanel>();
        }

        private void OnGuestLoginClick()
        {
            Debug.Log("[SDK] 游客登录");
            SDKManager.Instance.LoginSuccess("Guest_" + Random.Range(1000, 9999));
            SDKUIManager.Instance.PopPanel();
            SDKUIManager.Instance.ShowPanel<RealNameAuthPanel>();
        }

        private void ShowTip(string msg)
        {
            tipText.text = msg;
        }

        public override void OnEnter()
        {
            base.OnEnter();
            usernameInput.text = "";
            passwordInput.text = "";
            tipText.text = "";
        }
    }
}
