using UnityEngine;
using UnityEngine.UI;
using TMPro;

namespace GameSDK
{
    /// <summary>
    /// 注册面板
    /// </summary>
    public class RegisterPanel : BasePanel
    {
        [Header("UI References")]
        public TMP_InputField usernameInput;
        public TMP_InputField passwordInput;
        public TMP_InputField confirmPasswordInput;
        public Button registerBtn;
        public Button backBtn;
        public TMP_Text tipText;

        private bool initialized;

        private void OnEnable()
        {
            if (initialized) return;
            initialized = true;
            registerBtn.onClick.AddListener(OnRegisterClick);
            backBtn.onClick.AddListener(OnBackClick);
        }

        private void OnDisable()
        {
            if (!initialized) return;
            initialized = false;
            registerBtn.onClick.RemoveListener(OnRegisterClick);
            backBtn.onClick.RemoveListener(OnBackClick);
        }

        private void OnDestroy()
        {
            initialized = false;
            if (registerBtn != null) registerBtn.onClick.RemoveListener(OnRegisterClick);
            if (backBtn != null) backBtn.onClick.RemoveListener(OnBackClick);
        }

        private void OnRegisterClick()
        {
            string username = usernameInput.text.Trim();
            string password = passwordInput.text.Trim();
            string confirmPassword = confirmPasswordInput.text.Trim();

            if (string.IsNullOrEmpty(username))
            {
                ShowTip("请输入账号");
                return;
            }
            if (username.Length < 4 || username.Length > 20)
            {
                ShowTip("账号长度需在4-20个字符之间");
                return;
            }
            if (string.IsNullOrEmpty(password))
            {
                ShowTip("请输入密码");
                return;
            }
            if (password.Length < 6)
            {
                ShowTip("密码长度不能少于6位");
                return;
            }
            if (password != confirmPassword)
            {
                ShowTip("两次输入的密码不一致");
                return;
            }

            // TODO: 接入实际注册接口
            Debug.Log($"[SDK] 注册请求: 账号={username}");
            ShowTip("注册中...");

            // 模拟注册成功
            Debug.Log("[SDK] 注册成功");
            SDKUIManager.Instance.PopPanel();
        }

        private void OnBackClick()
        {
            SDKUIManager.Instance.PopPanel();
        }

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

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