using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using _Core;
using _Combo;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Seayoo.ComboSDK.Windows.Account.Model.VO;

namespace Seayoo.ComboSDK.Windows.Account.View
{
    public class SeayooAccountPhoneLoginView : MonoBehaviour
    {
        public InputField phoneNumberInputFiled;
        public Button enterNextPageBtn;
        public Button taptapLoginBtn;
        public Button backBtn;
        public Button closeBtn;
        public Toggle privacyToggle;
        public Text phoneNumberPlaceHolder;
        public Text otherLoginText;
        public Text titleText;
        public HyperlinkText privacyText;
        public GameObject otherLoginTypePanel;
        public GameObject logoImage;
        public GameObject privacyPanel;
        public Image mask;
        public RectTransform logoPanel;
        public RectTransform contentPanel;
        public RectTransform allPanel;
        private const int MOBILE_LENGTH = 11;

        void Awake()
        {
            EventSystem.Register(this);
            gameObject.SetActive(false);
            titleText.text = I18n.T("login_default_title");
            phoneNumberPlaceHolder.text = I18n.T("login_or_register_mobile_placeholder");
            otherLoginText.text = I18n.T("login_other_methods_text");
            otherLoginTypePanel.gameObject.SetActive(IsContainsOtherModules() && !GlobalParameters.Instance.TaptapDisableTapLogin);
            if (GlobalParameters.Instance.SeayooAccountHideLogo)
            {
                logoImage.gameObject.SetActive(false);
                titleText.text = I18n.T("login_title");
            }
            if (GlobalParameters.Instance.SeayooAccountHideCloseButton)
            {
                closeBtn.gameObject.SetActive(false);
            }
        }

        void Start()
        {
            backBtn.onClick.AddListener(OnBack);
            enterNextPageBtn.onClick.AddListener(OnEnterNextPageView);
            taptapLoginBtn.onClick.AddListener(TapTapLogin);
            closeBtn.onClick.AddListener(OnClose);
            phoneNumberInputFiled.onValueChanged.AddListener(OnCheckPhoneNumber);
            phoneNumberInputFiled.onEndEdit.AddListener(OnInputEndEdit);
        }

        void OnDestroy()
        {
            EventSystem.UnRegister(this);
            backBtn.onClick.RemoveListener(OnBack);
            enterNextPageBtn.onClick.RemoveListener(OnEnterNextPageView);
            taptapLoginBtn.onClick.RemoveListener(TapTapLogin);
            closeBtn.onClick.RemoveListener(OnClose);
            phoneNumberInputFiled.onValueChanged.RemoveListener(OnCheckPhoneNumber);
            phoneNumberInputFiled.onEndEdit.RemoveListener(OnInputEndEdit);
        }

        [EventSystem.BindEvent]
        void OnGoToView(GoToViewCommand action)
        {
            if (action.viewType != SeayooAccountViewType.PHONE)
            {
                Hide();
                return;
            }

            Show();
        }

        private void OnCheckPhoneNumber(string newValue)
        {
            enterNextPageBtn.gameObject.SetActive(newValue.Length == MOBILE_LENGTH);
        }

        void OnInputEndEdit(string text)
        {
            if (text.Length > 0 && text.Length < 11)
            {
                UIController.Instance.ShowToast(I18n.T("mobile_invalid_toast"));
            }
        }

        private void OnEnterNextPageView()
        {
            if (!privacyToggle.isOn)
            {
                string text = I18n.T("login_agreements_text", new Dictionary<string, object>()
                {
                    {"0", Config.userAgreement},
                    {"1", I18n.T("login_user_agreements_text")},
                    {"2", Config.privacyPolicy},
                    {"3", I18n.T("login_privacy_policy_text")}
                });
                UIController.Instance.ShowAlertView
                (
                    I18n.T("login_privacy_agree_dialog_title"),
                    text,
                    TextAnchor.UpperCenter,
                    I18n.T("cancel_button"),
                    I18n.T("login_privacy_agree_button"),
                    () => { },
                    () =>
                    {
                        privacyToggle.isOn = true;
                        GoToNextView();
                    }
                );

            }
            else
            {
                GoToNextView();
            }
        }

        private void GoToNextView()
        {
            GetLoginOptionsCommand.Invoke(new GetLoginOptionsCommand
            {
                account = phoneNumberInputFiled.text,
                OnSuccess = res =>
                {
                    UIController.Instance.HideLoading();
                    if (!res.password)
                    {
                        // 密码不可用
                        GoToViewCommand.Invoke(new GoToViewCommand
                        {
                            viewType = SeayooAccountViewType.CAPTCHA_OR_PASSWORD,
                            vo = new LoginOptionsVO
                            {
                                opt = true,
                                account = phoneNumberInputFiled.text
                            }
                        });
                    }
                    else
                    {
                        // 密码可用
                        GoToViewCommand.Invoke(new GoToViewCommand
                        {
                            viewType = SeayooAccountViewType.CAPTCHA_OR_PASSWORD,
                            vo = new LoginOptionsVO
                            {
                                opt = false,
                                account = phoneNumberInputFiled.text
                            }
                        });
                    }
                },
                OnFail = (err) =>
                {
                    UIController.Instance.HideLoading();
                    var serverError = ErrorExtensions.Convert<ServerError>(err);
                    if (serverError == null)
                        return;
                    var serverErrorCode = serverError.Error ?? "";
                    if (serverErrorCode == "mobile_not_in_allowlist")
                    {
                        UIController.Instance.ShowAlertView(
                        I18n.T("common_dialog_title"),
                        serverError.ErrorMsg.Replace(" ", "\u00A0"),
                        TextAnchor.UpperLeft,
                        I18n.T("acknowledge_button"),
                        () => { });
                    }
                    else
                    {
                        UIController.Instance.ShowToast(serverError.ErrorMsg);
                    }
                }
            });
        }

        public void OnClose()
        {
            CloseWindowCommand.Invoke(new CloseWindowCommand
            {
                userCancel = true
            });
        }

        public void Show()
        {
            gameObject.SetActive(true);
            
            LayoutRebuilder.ForceRebuildLayoutImmediate(logoPanel);
            LayoutRebuilder.ForceRebuildLayoutImmediate(contentPanel);
            LayoutRebuilder.ForceRebuildLayoutImmediate(allPanel);
            mask.color = new Color(0f, 0f, 0f, 0.3f);
            Clear();
            if (Config.hideEula)
            {
                privacyPanel.gameObject.SetActive(false);
                privacyToggle.isOn = true;
            }
            backBtn.gameObject.SetActive(UserHistoryManager.Instance.GetUsers().Count != 0);

            privacyText.text = I18n.T("login_agreements_default_text", new Dictionary<string, object>()
            {
                {"0", Config.userAgreement},
                {"1", I18n.T("login_user_agreements_text")},
                {"2", Config.privacyPolicy},
                {"3", I18n.T("login_privacy_policy_text")}
            });
            StartCoroutine(SetHyperlinkActionsDelayed());
        }

        private IEnumerator SetHyperlinkActionsDelayed()
        {
            // 等待一帧，确保 OnPopulateMesh 执行
            yield return null;

            privacyText.SetHyperlinkClickActions(new Dictionary<string, System.Action<string>>{
                {
                    Config.userAgreement, (link)=>{
#if UNITY_STANDALONE
                        UIController.Instance.ShowWebView(link, WebViewType.General, 100, 100);
#endif
                }},
                {
                    Config.privacyPolicy, (link)=>{
#if UNITY_STANDALONE
                        UIController.Instance.ShowWebView(link, WebViewType.General, 100, 100);
#endif
                }}
            });
        }

        private void Clear()
        {
            phoneNumberInputFiled.text = "";
            privacyToggle.isOn = false;
        }

        public void Hide()
        {
            gameObject.SetActive(false);
        }

        public void OnBack()
        {
            GoToViewCommand.Invoke(new GoToViewCommand
            {
                viewType = SeayooAccountViewType.TOKEN
            });
        }

        public void TapTapLogin()
        {
            if (!privacyToggle.isOn)
            {
                string text = I18n.T("login_agreements_text", new Dictionary<string, object>()
                {
                    {"0", Config.userAgreement},
                    {"1", I18n.T("login_user_agreements_text")},
                    {"2", Config.privacyPolicy},
                    {"3", I18n.T("login_privacy_policy_text")}
                });
                UIController.Instance.ShowAlertView
                (
                    I18n.T("login_privacy_agree_dialog_title"),
                    text,
                    TextAnchor.UpperCenter,
                    I18n.T("cancel_button"),
                    I18n.T("login_privacy_agree_button"),
                    () => { },
                    () =>
                    {
                        privacyToggle.isOn = true;
                        TapTap.TapTap.Instance.Login();
                        Hide();
                    }
                );
                return;
            }
            TapTap.TapTap.Instance.Login();
            Hide();
        }

        private bool IsContainsOtherModules()
        {
            if (Configuration.Instance.Modules.Contains("taptap"))
            {
                return true;
            }
            return false;
        }
    }
}
