using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using _Core;
using _Combo;
using System;

namespace Seayoo.ComboSDK.Windows.Account.View
{
    public class SeayooAccountTokenLoginView : MonoBehaviour
    {
        public Button closeBtn;
        public Button enterGameBtn;
        public Button otherAccountBtn;
        public Dropdown dropdown;
        public Text loginText;
        public Text enterGameText;
        public Text otherAccountText;
        public Text currentTimePhoneNumberText;
        public Text timeText;
        public GameObject logoImage;
        public Image mask;
        public Image arrow;
        public Sprite arrowUpSprite;
        public Sprite arrowDownSprite;
        public RectTransform inputPanel;
        public RectTransform logoPanel;
        public RectTransform contentPanel;
        public RectTransform allPanel;
        void Awake()
        {
            EventSystem.Register(this);
            loginText.text = I18n.T("login_default_title");
            enterGameText.text = I18n.T("login_submit_button");
            otherAccountText.text = I18n.T("login_other_accounts_button");
            gameObject.SetActive(false);
            if (GlobalParameters.Instance.SeayooAccountHideLogo)
            {
                logoImage.gameObject.SetActive(false);
                loginText.text = I18n.T("login_title");
            }
            if(GlobalParameters.Instance.SeayooAccountHideCloseButton)
            {
                closeBtn.gameObject.SetActive(false);
            }
        }

        void Start()
        {
            closeBtn.onClick.AddListener(OnClose);
            enterGameBtn.onClick.AddListener(OnEnterGame);
            otherAccountBtn.onClick.AddListener(OnLoginOtherAccount);
            dropdown.onValueChanged.AddListener(HandleDropdownValueChanged);
        }

        void OnDestroy()
        {
            closeBtn.onClick.RemoveListener(OnClose);
            enterGameBtn.onClick.RemoveListener(OnEnterGame);
            otherAccountBtn.onClick.RemoveListener(OnLoginOtherAccount);
            EventSystem.UnRegister(this);
        }

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

            Show();
        }

        [EventSystem.BindEvent]
        void DropdownTemplateIsShow(DropdownTemplateIsShowCommand action)
        {
            if (action.isShow)
            {
                arrow.sprite = arrowUpSprite;
            }
            else
            {
                arrow.sprite = arrowDownSprite;
            }
        }

        private void HandleDropdownValueChanged(int value)
        {
            var histories = UserHistoryManager.Instance.GetUsers();
            currentTimePhoneNumberText.text = histories[value].mobileMask;
            if (histories[value].isRecentLogin)
            {
                timeText.text = I18n.T("login_token_time_show_recent");
            }
            else
            {
                timeText.text = GetTimeDescription(histories[value].time);
            }   
        }

        public void ClickDropdowItem(string mobileMask)
        {
            UIController.Instance.ShowAlertView(
                I18n.T("common_dialog_title"),
                I18n.T("login_delete_credential_dialog_text"),
                TextAnchor.UpperCenter,
                I18n.T("cancel_button"),
                I18n.T("delete_button"),
                () => { },
                () =>
                {
                    var option = dropdown.options.Find(o => string.Equals(o.text, mobileMask));
                    dropdown.options.Remove(option);
                    dropdown.Hide();
                    dropdown.RefreshShownValue();
                    var userId = UserHistoryManager.Instance.FindUserHistory(mobileMask).userId;
                    DeleteUserHistoryCommand.Invoke(new DeleteUserHistoryCommand { userId = userId });
                },
                32767
            );
        }

        public void OnEnterGame()
        {
            enterGameBtn.interactable = false;
            var user = UserHistoryManager.Instance.FindUserHistory(dropdown.value);
            TokenLoginCommand.Invoke(new TokenLoginCommand
            {
                userId = user.userId,
                token = user.token,
            });
        }

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

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

        [EventSystem.BindEvent]
        public void Refresh(RefreshViewCommand action = null)
        {
            var histories = UserHistoryManager.Instance.GetUsers();

            dropdown.ClearOptions();
            var options = new List<Dropdown.OptionData>(histories.Count);
            histories.ForEach(record =>
            {
                string text;
                if (record.isRecentLogin)
                {
                    text = $"<color=#13243D>{record.mobileMask}</color>  <size=22><color=#ADB1C9>{I18n.T("login_token_time_show_recent")}</color></size>";
                }
                else
                {
                    text = $"<color=#13243D>{record.mobileMask}</color>  <size=22><color=#ADB1C9>{GetTimeDescription(record.time)}</color></size>";
                }
                
                options.Add(new Dropdown.OptionData(text));
            });
            dropdown.options = options;
            enterGameBtn.interactable = true;
            if (histories.Count == 0)
                return;
            currentTimePhoneNumberText.text = histories[0].mobileMask;
            if (histories[0].isRecentLogin)
            {
                timeText.text = I18n.T("login_token_time_show_recent");
            }
            else
            {
                timeText.text = GetTimeDescription(histories[0].time);
            }   
        }

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

        public void OnLoginOtherAccount()
        {
            GoToViewCommand.Invoke(new GoToViewCommand
            {
                viewType = SeayooAccountViewType.PHONE,
            });
        }
        
        private string GetTimeDescription(long previousTimestamp)
        {
            long currentTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds();

            long timeDifference = currentTimestamp - previousTimestamp;

            double daysDifference = timeDifference / 86400.0;

            if (daysDifference < 1)
            {
                return I18n.T("login_token_time_show_today");
            }
            else if (daysDifference < 2)
            {
                return I18n.T("login_token_time_show_yesterday");
            }
            else if (daysDifference >= 2 && daysDifference < 7)
            {
                return I18n.T("login_token_time_show_3_day_ago");
            }
            else if (daysDifference >= 7 && daysDifference < 30)
            {
                return I18n.T("login_token_time_show_7_day_ago");
            }
            else
            {
                return I18n.T("login_token_time_show_30_day_ago");
            }
        }
    }
}
