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

namespace Seayoo.ComboSDK.Windows.Account.View
{
    public class SeayooAccountLinkIdentityView : MonoBehaviour
    {
        public Button getOTPBtn;
        public Button linkIdentityBtn;
        public Button closeBtn;
        public Button backBtn;
        public InputField phoneNumber;
        public InputField captcha;
        public Text countdownTxt;
        public Text captchaPlaceHolder;
        public Text phoneNumberPlaceHolder;
        public Text linkInfoText;
        public Text titleText;
        public Text linkText;
        public Image mask;
        private Coroutine countdownCoroutine;
        public PhoneLoginVO vo = new PhoneLoginVO();
        private Credential credential = new Credential();

        private const int MOBILE_LENGTH = 11;
        private const int CAPTCHA_LENGTH = 6;

        void Awake()
        {
            captchaPlaceHolder.text = I18n.T("mobile_otp_placeholder");
            countdownTxt.text = I18n.T("mobile_send_otp_button");
            phoneNumberPlaceHolder.text = I18n.T("login_or_register_mobile_placeholder");
            linkText.text = I18n.T("login_submit_button");
            if(GlobalParameters.Instance.SeayooAccountHideCloseButton)
            {
                closeBtn.gameObject.SetActive(false);
            }
            if(GlobalParameters.Instance.SeayooAccountHideLogo)
            {
                linkInfoText.text = I18n.T("link_seayoo_account_anon_text");
                titleText.text = I18n.T("link_seayoo_account_anon_title");
            }
            else
            {
                linkInfoText.text = I18n.T("link_seayoo_account_default_text");
                titleText.text = I18n.T("link_seayoo_account_default_title");
            }
            EventSystem.Register(this);
            gameObject.SetActive(false);
        }

        void Start()
        {
            getOTPBtn.onClick.AddListener(OnGetOTP);
            captcha.onValueChanged.AddListener(OnOTPnputFieldValueChanged);
            phoneNumber.onValueChanged.AddListener(OnMobileInputFieldValueChanged);
            closeBtn.onClick.AddListener(OnClose);
            linkIdentityBtn.onClick.AddListener(LinkIdentity);
            backBtn.onClick.AddListener(OnBackLoginView);
        }

        void OnDestroy()
        {
            getOTPBtn.onClick.RemoveListener(OnGetOTP);
            captcha.onValueChanged.RemoveListener(OnOTPnputFieldValueChanged);
            phoneNumber.onValueChanged.RemoveListener(OnMobileInputFieldValueChanged);
            closeBtn.onClick.RemoveListener(OnClose);
            linkIdentityBtn.onClick.RemoveListener(LinkIdentity);
            backBtn.onClick.RemoveListener(OnBackLoginView);
            EventSystem.UnRegister(this);
        }

        public void LinkIdentity()
        {
            if(!CheckMobile())
            {
                return;
            }
            if (string.IsNullOrEmpty(vo.otpAction))
            {
                UIController.Instance.ShowToast(I18n.T("otp_not_sent_toast"));
                return;
            }
            if(!CheckCaptcha())
            {
                return;
            }
            LinkIdentityCommand.Invoke(new LinkIdentityCommand()
            {
                mobile = phoneNumber.text,
                otp = captcha.text,
                action = vo.otpAction,
                credential = credential
            });
        }

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

            credential = (Credential)action.vo;
            Show();
        }

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

        public void OnBackLoginView()
        {
            GoToViewCommand.Invoke(new GoToViewCommand
            {
                viewType = SeayooAccountViewType.PHONE
            });
        }

        public void UpdateCountdown(bool isRun)
        {
            if (isRun)
            {
                countdownCoroutine = StartCoroutine(StartCountdown(60));
            }
            else
            {
                if (countdownCoroutine != null)
                {
                    StopCoroutine(countdownCoroutine);
                    countdownCoroutine = null;
                }
                SetGetOTPButtonState(true);
            }
        }

        IEnumerator StartCountdown(int totalTime)
        {
            SetGetOTPButtonState(false);

            int remainingTime = totalTime;
            float startTime = Time.realtimeSinceStartup;
            float countdownDuration = remainingTime;

            while (remainingTime > 0)
            {
                float elapsedTime = Time.realtimeSinceStartup - startTime;
                remainingTime = Mathf.CeilToInt(countdownDuration - elapsedTime);

                if (remainingTime <= 0)
                {
                    SetGetOTPButtonState(true, I18n.T("mobile_resend_otp_button"));
                    yield return null;
                }
                else
                {
                    countdownTxt.text = remainingTime + "s";
                    yield return new WaitForSecondsRealtime(1f);
                }
            }
        }

        void SetGetOTPButtonState(bool enabled, string retryText = "")
        {
            if (enabled)
            {
                getOTPBtn.interactable = true;
                if (string.IsNullOrEmpty(retryText))
                {
                    countdownTxt.text = I18n.T("mobile_send_otp_button");
                }
                else
                {
                    countdownTxt.text = retryText;
                }
                countdownTxt.color = new Color(0.267f, 0.361f, 0.921f);
            }
            else
            {
                countdownTxt.color = Color.black;
                getOTPBtn.interactable = false;
            }
        }

        public void OnGetOTP()
        {
            if (!CheckMobile())
            {
                return;
            };
            getOTPBtn.interactable = false;
            CreateCaptchaCommand.Invoke(new CreateCaptchaCommand {
                account = phoneNumber.text,
                action = SeayooAccountPhoneLoginViewTypeCode.ConvertToModule(SeayooAccountPhoneLoginViewType.CAPTCHA),
                OnSuccess = resp => {
                    getOTPBtn.interactable = true;
                    if(resp.captchaId == "")
                    {
                        UIController.Instance.ShowToast(I18n.T("create_captcha_id_null_toast"));
                        return;
                    }
                    if(!string.IsNullOrEmpty(resp.captchaProvider) && !string.IsNullOrEmpty(resp.captchaConfig))
                    {
                        var otherData = new Dictionary<string, string>
                        {
                            { "captcha_id", resp.captchaId },
                            { "captcha_provider", resp.captchaProvider},
                            { "captcha_config", resp.captchaConfig}
                        };
                        string otherDataStr = string.Join("&", otherData.Select(kv => $"{kv.Key}={WebUtility.UrlEncode(kv.Value)}"));
                        string languageStr = string.Join("&", new Dictionary<string, string>{{"lang", I18n.GetLanguageCode()}}.Select(kv => $"{kv.Key}={WebUtility.UrlEncode(kv.Value)}"));
                        string url = $"{GlobalParameters.Instance.SeayooAccountCaptchaUrl}?{otherDataStr}&{languageStr}";
#if UNITY_STANDALONE
                        UIController.Instance.ShowWebView(url, WebViewType.LinkCreateCaptcha, 100, 100, false, true);
#endif
                    }
                    else
                    {
                        CreateLoginOTPCommand.Invoke(new CreateLoginOTPCommand { 
                            mobile = phoneNumber.text, 
                            captchaId = resp.captchaId,
                            OnSuccess = action => {
                                UIController.Instance.ShowToast(I18n.T("otp_sent_sms_toast"));
                                vo.otpAction = action;
                                UpdateCountdown(true);
                                UIController.Instance.HideLoading();
                            },
                            OnFail = () => {
                                UpdateCountdown(false);
                                UIController.Instance.HideLoading();
                            }
                        });
                    }
                },
                OnFail = () => {
                    getOTPBtn.interactable = true;
                    UpdateCountdown(false);
                    UIController.Instance.HideLoading();
                }
            });
        }

        [EventSystem.BindEvent]
        public void CaptchaResult(ReceiveCaptchaResult result)
        {
            if(result.webViewType != WebViewType.LinkCreateCaptcha)
            {
                return;
            }
            CreateLoginOTPCommand.Invoke(new CreateLoginOTPCommand { 
                mobile = phoneNumber.text, 
                captchaId = result.captchaId,
                captchaResult = result.captchaResult,
                OnSuccess = action => {
                    UIController.Instance.ShowToast(I18n.T("otp_sent_sms_toast"));
                    vo.otpAction = action;
                    UpdateCountdown(true);
                    UIController.Instance.HideLoading();
                },
                OnFail = () => {
                    UpdateCountdown(false);
                    UIController.Instance.HideLoading();
                }
            });
        }

        public bool CheckCaptcha()
        {
            if (string.IsNullOrEmpty(captcha.text))
            {
                UIController.Instance.ShowToast(I18n.T("otp_required_toast"));
                return false;
            }
            if (captcha.text.Length != CAPTCHA_LENGTH)
            {
                UIController.Instance.ShowToast(I18n.T("otp_invalid_toast"));
                return false;
            }
            return true;
        }


        public bool CheckMobile()
        {
            if (string.IsNullOrEmpty(phoneNumber.text))
            {
                UIController.Instance.ShowToast(I18n.T("mobile_required_toast"));
                return false;
            }
            if (phoneNumber.text.Length != MOBILE_LENGTH)
            {
                UIController.Instance.ShowToast(I18n.T("mobile_invalid_toast"));
                return false;
            }
            return true;
        }

        private void OnOTPnputFieldValueChanged(string value)
        {
            captcha.text = value.Replace(" ", "");
            if (captcha.text.Length == CAPTCHA_LENGTH)
            {
                LinkIdentity();
            }
        }
        
        private void OnMobileInputFieldValueChanged(string value)
        {
            phoneNumber.text = value.Replace(" ", "");
        }

        private void ClearCaptcha()
        {
            captcha.text = "";
        }

        private void ClearMobile()
        {
            phoneNumber.text = "";
        }

        public void Show()
        {
            mask.color = new Color(0f, 0f, 0f, 0.3f);
            ClearMobile();
            ClearCaptcha();
            UpdateCountdown(false);
            gameObject.SetActive(true);
        }

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