using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using _Combo;
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 SeayooAccountCaptchaOrPasswordLoginView : MonoBehaviour
    {
        public Button backBtn;
        public Button closeBtn;
        public Button changeLoginOptionsBtn;
        public Button enterGameBtn;
        public Button getOTPBtn;
        public Button selectReadPasswordBtn;
        public Text tipText;
        public Text captchaPlaceHolder;
        public Text countdownText;
        public Text passwordPlaceHolder;
        public Text changeLoginOptionsText;
        public Text titleText;
        public InputField captchaInputFiled;
        public InputField passwordInputFiled;
        public Image selectReadPasswordBtnImage;
        public Sprite readPasswordSprite;
        public Sprite notReadPasswordSripte;
        public GameObject captchaPanel;
        public GameObject passwordPanel;
        public GameObject logoImage;
        public VerticalLayoutGroup verticalLayoutGroup;
        public Image mask;
        public RectTransform inputPanel;
        public RectTransform logoPanel;
        public RectTransform contentPanel;
        public RectTransform allPanel;
        private LoginOptionsVO vo;
        private Coroutine countdownCoroutine;
        private SeayooAccountPhoneLoginViewType type;
        private string action;
        private int CAPTCHA_LENGTH = 6;
        private int PASSWORD_LENGTH = 8;

        void Awake()
        {
            EventSystem.Register(this);
            gameObject.SetActive(false);
            titleText.text = I18n.T("login_default_title");
            captchaPlaceHolder.text = I18n.T("mobile_otp_placeholder");
            passwordPlaceHolder.text = I18n.T("password_placeholder");
            if (GlobalParameters.Instance.SeayooAccountHideLogo)
            {
                logoImage.gameObject.SetActive(false);
                titleText.text = I18n.T("login_title");
            }
            if(GlobalParameters.Instance.SeayooAccountHideCloseButton)
            {
                closeBtn.gameObject.SetActive(false);
            }
        }

        void Start()
        {
            getOTPBtn.onClick.AddListener(OnGetOTP);
            backBtn.onClick.AddListener(BackView);
            closeBtn.onClick.AddListener(OnClose);
            changeLoginOptionsBtn.onClick.AddListener(OnChangeLoginOptions);
            selectReadPasswordBtn.onClick.AddListener(IsReadPassword);
            enterGameBtn.onClick.AddListener(OnEnterGame);
            captchaInputFiled.onValueChanged.AddListener(OnCaptchaieldChanged);
        }

        void OnDestroy()
        {
            EventSystem.UnRegister(this);
            getOTPBtn.onClick.RemoveListener(OnGetOTP);
            backBtn.onClick.RemoveListener(BackView);
            closeBtn.onClick.RemoveListener(OnClose);
            changeLoginOptionsBtn.onClick.RemoveListener(OnChangeLoginOptions);
            selectReadPasswordBtn.onClick.RemoveListener(IsReadPassword);
            enterGameBtn.onClick.RemoveListener(OnEnterGame);
            captchaInputFiled.onValueChanged.RemoveListener(OnCaptchaieldChanged);
        }

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

            vo = (LoginOptionsVO)action.vo;
            Show();
        }

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

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

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

        public void Show()
        {
            gameObject.SetActive(true);
            LayoutRebuilder.ForceRebuildLayoutImmediate(inputPanel);
            LayoutRebuilder.ForceRebuildLayoutImmediate(logoPanel);
            LayoutRebuilder.ForceRebuildLayoutImmediate(contentPanel);
            LayoutRebuilder.ForceRebuildLayoutImmediate(allPanel);
            mask.color = new Color(0f, 0f, 0f, 0.3f);
            action = "";
            UpdateCountdown(false);
            if (vo.opt)
            {
                CaptchaLoginShow();
                OnGetOTP();
                changeLoginOptionsBtn.gameObject.SetActive(false);
                captchaInputFiled.text = "";
                verticalLayoutGroup.padding.bottom = 94;
                return;
            }
            PasswordLoginShow();
            passwordInputFiled.text = "";
            changeLoginOptionsBtn.gameObject.SetActive(true);
            verticalLayoutGroup.padding.bottom = 74;
        }


        public void OnCaptchaieldChanged(string newValue)
        {
            captchaInputFiled.text = newValue.Replace(" ", "");
            if (captchaInputFiled.text.Length == CAPTCHA_LENGTH)
            {
                OnEnterGame();
            }
        }

        public void OnEnterGame()
        {
            if (type == SeayooAccountPhoneLoginViewType.CAPTCHA)
            {
                if (string.IsNullOrEmpty(action))
                {
                    UIController.Instance.ShowToast(I18n.T("otp_not_sent_toast"));
                    return;
                }
                if (string.IsNullOrEmpty(captchaInputFiled.text))
                {
                    UIController.Instance.ShowToast(I18n.T("otp_required_toast"));
                    return;
                }
                if (captchaInputFiled.text.Length != CAPTCHA_LENGTH)
                {
                    UIController.Instance.ShowToast(I18n.T("otp_invalid_toast"));
                    return;
                }
                PhoneLoginCommand.Invoke(new PhoneLoginCommand
                {
                    mobile = vo.account,
                    otp = captchaInputFiled.text,
                    action = action,
                });
            }
            else
            {
                if (string.IsNullOrEmpty(passwordInputFiled.text))
                {
                    UIController.Instance.ShowToast(I18n.T("password_required_toast"));
                    return;
                }
                if (passwordInputFiled.text.Length < PASSWORD_LENGTH)
                {
                    UIController.Instance.ShowToast(I18n.T("password_invalid_toast"));
                    return;
                }
                CreateCaptchaCommand.Invoke(new CreateCaptchaCommand
                {
                    account = vo.account,
                    action = SeayooAccountPhoneLoginViewTypeCode.ConvertToModule(SeayooAccountPhoneLoginViewType.PASSWORD),
                    OnSuccess = resp =>
                    {
                        UIController.Instance.HideLoading();
                        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.PasswordCreateCaptcha, 100, 100, false, true);
#endif
                        }
                        else
                        {
                            PasswordLoginCommand.Invoke(new PasswordLoginCommand
                            {
                                username = vo.account,
                                password = passwordInputFiled.text,
                                encrypted = false,
                                captchaId = resp.captchaId,
                            });
                        }
                    },
                    OnFail = () =>
                    {
                        UIController.Instance.HideLoading();
                    }
                });

            }
        }

        [EventSystem.BindEvent]
        public void CaptchaResult(ReceiveCaptchaResult result)
        {
            if (result.webViewType == WebViewType.PasswordCreateCaptcha)
            {
                PasswordLoginCommand.Invoke(new PasswordLoginCommand
                {
                    username = vo.account,
                    password = passwordInputFiled.text,
                    encrypted = false,
                    captchaId = result.captchaId,
                    captchaResult = result.captchaResult
                });
            }
            if (result.webViewType == WebViewType.OtpCreateCaptcha)
            {
                CreateLoginOTPCommand.Invoke(new CreateLoginOTPCommand
                {
                    mobile = vo.account,
                    captchaId = result.captchaId,
                    captchaResult = result.captchaResult,
                    OnSuccess = action =>
                    {
                        this.action = action;
                        UpdateCountdown(true);
                        tipText.text = I18n.T("device_grant_send_otp_text", new Dictionary<string, object>
                        {
                            { "0",  $"{vo.account.Substring(0, 3)} {vo.account.Substring(3, 4)} {vo.account.Substring(7, 4)}"}
                        });
                        UIController.Instance.HideLoading();
                    },
                    OnFail = () =>
                    {
                        UpdateCountdown(false);
                        UIController.Instance.HideLoading();
                    }
                });
            }
        }

        public void OnChangeLoginOptions()
        {
            if (type == SeayooAccountPhoneLoginViewType.CAPTCHA)
            {
                PasswordLoginShow();
                return;
            }
            CaptchaLoginShow();
        }

        private void CaptchaLoginShow()
        {
            type = SeayooAccountPhoneLoginViewType.CAPTCHA;
            captchaPanel.gameObject.SetActive(true);
            passwordPanel.gameObject.SetActive(false);
            if (string.IsNullOrEmpty(action))
            {
                tipText.text = I18n.T("device_grant_send_otp_default_text", new Dictionary<string, object>
                {
                    { "0",  $"{vo.account.Substring(0, 3)} {vo.account.Substring(3, 4)} {vo.account.Substring(7, 4)}"}
                });
            }
            else
            {
                tipText.text = I18n.T("device_grant_send_otp_text", new Dictionary<string, object>
                {
                    { "0",  $"{vo.account.Substring(0, 3)} {vo.account.Substring(3, 4)} {vo.account.Substring(7, 4)}"}
                });
            }
            changeLoginOptionsText.text = I18n.T("login_password_tab");
        }

        private void PasswordLoginShow()
        {
            type = SeayooAccountPhoneLoginViewType.PASSWORD;
            captchaPanel.gameObject.SetActive(false);
            passwordPanel.gameObject.SetActive(true);
            tipText.text = I18n.T("password_login_text", new Dictionary<string, object>
            {
                { "0", $"{vo.account.Substring(0, 3)} {vo.account.Substring(3, 4)} {vo.account.Substring(7, 4)}" }
            });
            changeLoginOptionsText.text = I18n.T("login_otp_button");
        }

        public void IsReadPassword()
        {
            if (passwordInputFiled.contentType == InputField.ContentType.Standard)
            {
                passwordInputFiled.contentType = InputField.ContentType.Password;
                selectReadPasswordBtnImage.sprite = notReadPasswordSripte;
            }
            else
            {
                passwordInputFiled.contentType = InputField.ContentType.Standard;
                selectReadPasswordBtnImage.sprite = readPasswordSprite;
            }
            passwordInputFiled.ForceLabelUpdate();
        }

        public void OnGetOTP()
        {
            getOTPBtn.interactable = false;

            CreateCaptchaCommand.Invoke(new CreateCaptchaCommand {
                account = vo.account,
                action = SeayooAccountPhoneLoginViewTypeCode.ConvertToModule(SeayooAccountPhoneLoginViewType.CAPTCHA),
                OnSuccess = resp => {
                    getOTPBtn.interactable = true;
                    UIController.Instance.HideLoading();
                    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.OtpCreateCaptcha, 100, 100, false, true);
#endif
                    }
                    else
                    {
                        CreateLoginOTPCommand.Invoke(new CreateLoginOTPCommand
                        {
                            mobile = vo.account,
                            captchaId = resp.captchaId,
                            OnSuccess = action =>
                            {
                                this.action = action;
                                UpdateCountdown(true);
                                UIController.Instance.HideLoading();
                                tipText.text = I18n.T("device_grant_send_otp_text", new Dictionary<string, object>
                                {
                                    { "0",  $"{vo.account.Substring(0, 3)} {vo.account.Substring(3, 4)} {vo.account.Substring(7, 4)}"}
                                });
                            },
                            OnFail = () =>
                            {
                                UpdateCountdown(false);
                                UIController.Instance.HideLoading();
                            }
                        });
                    }
                },
                OnFail = () =>
                {
                    getOTPBtn.interactable = true;
                    UIController.Instance.HideLoading();
                }
            });
        }

        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
                {
                    countdownText.text = remainingTime + "s";
                    yield return new WaitForSecondsRealtime(1f);
                }
            }
        }

        void SetGetOTPButtonState(bool enabled, string retryText = "")
        {
            if (enabled)
            {
                getOTPBtn.interactable = true;
                if (string.IsNullOrEmpty(retryText))
                {
                    countdownText.text = I18n.T("mobile_send_otp_button");
                }
                else
                {
                    countdownText.text = retryText;
                }
                countdownText.color = new Color(0.267f, 0.361f, 0.921f);
            }
            else
            {
                countdownText.color = new Color(19/255f, 36/255f, 61/2551f);
                getOTPBtn.interactable = false;
            }
        }
    }
}