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

namespace Seayoo.ComboSDK.Windows.Account.View
{
    public class SeayooAccountDeviceGrantView : MonoBehaviour
    {
        public Button getOTPBtn;
        public Button closeBtn;
        public Button enterGameBtn;
        public Button backBtn;
        public Text countdownTxt;
        public Text tipText;
        public Text captchaPlaceHolder;
        public Text newDeviceText;
        public Text enterGameText;
        public InputField captcha;
        public Image mask;
        private Coroutine countdownCoroutine;
        private PasswordLoginVO vo;
        private bool getCaptcha = false;
        private int CAPTCHA_LENGTH = 6;

        void Awake()
        {
            EventSystem.Register(this);
            newDeviceText.text = I18n.T("device_grant_title");
            enterGameText.text = I18n.T("login_submit_button");
            gameObject.SetActive(false);
            if(GlobalParameters.Instance.SeayooAccountHideCloseButton)
            {
                closeBtn.gameObject.SetActive(false);
            }
        }

        void Start()
        {
            getOTPBtn.onClick.AddListener(OnGetOTP);
            closeBtn.onClick.AddListener(OnClose);
            enterGameBtn.onClick.AddListener(OnGrantDeviceWithOTP);
            backBtn.onClick.AddListener(OnBack);
            captcha.onValueChanged.AddListener(OnCaptchaieldChanged);
        }

        void OnDestroy()
        {
            EventSystem.UnRegister(this);
            getOTPBtn.onClick.RemoveListener(OnGetOTP);
            closeBtn.onClick.RemoveListener(OnClose);
            enterGameBtn.onClick.RemoveListener(OnGrantDeviceWithOTP);
            backBtn.onClick.RemoveListener(OnBack);
            captcha.onValueChanged.RemoveListener(OnCaptchaieldChanged);
        }


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

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

        [EventSystem.BindEvent]
        public void Refresh(RefreshViewCommand action = null)
        {
            enterGameBtn.interactable = true;
        }

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

        public void OnBack()
        {
            GoToViewCommand.Invoke(new GoToViewCommand
            {
                viewType = SeayooAccountViewType.CAPTCHA_OR_PASSWORD,
                vo = new LoginOptionsVO
                {
                    opt = false,
                    account = vo.phoneNumber
                }
            });
        }

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

        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);
                }
            }
        }

        private 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()
        {
            getOTPBtn.interactable = false;
            getCaptcha = true;
            CreateDeviceGrantOTPCommand.Invoke(new CreateDeviceGrantOTPCommand
            {
                ticket = vo.deviceGrantTicket,
                OnSuccess = action => {
                    tipText.text = I18n.T("device_grant_send_otp_text", new Dictionary<string, object>
                    {
                        { "0", $"{vo.mobile.Substring(0, 3)} {vo.mobile.Substring(3, 6)} {vo.mobile.Substring(9, 2)}"}
                    });
                    UIController.Instance.HideLoading();
                    UpdateCountdown(true);
                },
                OnFail = () => {
                    UIController.Instance.HideLoading();
                    UpdateCountdown(false);
                }
                
            });
        }

        public void OnGrantDeviceWithOTP()
        {
            if (!CheckCaptcha())
            {
                return;
            }
            GrantDeviceWithOTPCommand.Invoke(new GrantDeviceWithOTPCommand
            {
                ticket = vo.deviceGrantTicket,
                otp = captcha.text,
            });
        }

        public bool CheckCaptcha()
        {
            if (!getCaptcha)
            {
                UIController.Instance.ShowToast(I18n.T("otp_not_sent_toast"));
                return false;
            }
            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 void Show()
        {
            mask.color = new Color(0f, 0f, 0f, 0.3f);
            tipText.text = I18n.T("device_grant_send_otp_default_text", new Dictionary<string, object>
            {
                { "0", $"{vo.mobile.Substring(0, 3)} {vo.mobile.Substring(3, 6)} {vo.mobile.Substring(9, 2)}"}
            });
            gameObject.SetActive(true);
            countdownTxt.text = I18n.T("mobile_send_otp_button");
            OnGetOTP();
        }

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