using TMPro;
using System;
using System.Collections;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using Button = UnityEngine.UI.Button;

namespace Guru.UI
{
    
    /// <summary>
    /// UI主体组件
    /// </summary>
    public class UIRatingView: MonoBehaviour
    {
		//-----------------------组件绑定-----------------------------//
		[SerializeField] private RectTransform root;
		[SerializeField] private Button btnClose;
		[SerializeField] private CanvasGroup nodeRating;
		[SerializeField] private CanvasGroup nodeLowStar;
		[SerializeField] private CanvasGroup nodeThanks;
		[SerializeField] private UIRatingStars uiStars1;
		[SerializeField] private UIRatingStars uiStars2;
		[SerializeField] private Button btnOk;
		[SerializeField] private TextMeshProUGUI txtLowstarTitle;
		[SerializeField] private Text txtLowstarInfo;
		[SerializeField] private Button btnSubmit;
		[SerializeField] private InputField inputMsg;
		[SerializeField] private TMP_InputField tmpInput;
		
		public const string EMOJI_CRY = "\U0001F606";
		public const string EMOJI_HAPPY = "\U0001F600";

		private const int RATING_STATE_ENTER = 1;
		private const int RATING_STATE_FEEDBACK = 2;
		private const int RATING_STATE_THANKS = 3;

		private int _curState;
		private int _ratingValue;
		private Action<int, string> _ratingCallback;
		private bool _isRTL;

		public int State
		{
			get => _curState;
			set => SetState(value);
		}

		#region 生命周期

		private void Awake()
		{
			Init();
		}

		/// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
	        uiStars1.OnValueChanged = OnGetStarValue;
	        uiStars2.OnValueChanged = OnGetStarValue;
	        
	        AddButton(btnClose, OnClickCloseEvent);
	        AddButton(btnSubmit, OnClickSubmitEvent);
	        AddButton(btnOk, OnClickCloseEvent);

	        State = RATING_STATE_ENTER;
        }

		private void AddButton(Button btn, UnityAction callback)
		{
			btn.onClick.AddListener(callback);
		}


		private void Start()
		{
			OnOpen();
		}

		#endregion

        #region 初始化

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="callback"></param>
        public void InitWithData(Action<int, string> callback = null)
        {
	        _ratingCallback = callback;
	        UpdateLayout();
        }
        
        private void UpdateLayout()
        {
	        _isRTL = I2.Loc.LocalizationManager.IsRight2Left;
	        if (_isRTL)
	        {
		        var pos = btnClose.transform.localPosition;
		        pos.x *= -1;
		        btnClose.transform.localPosition = pos;
	        }

	        uiStars1.IsRTL = _isRTL;
	        uiStars2.IsRTL = _isRTL;

	        // tmpInput.textComponent.isRightToLeftText = isRtl;
	        

	        if (_isRTL)
	        {
		        inputMsg.gameObject.SetActive(false);
		        tmpInput.gameObject.SetActive(true);
		        tmpInput.textComponent.isRightToLeftText = true;
		        tmpInput.textComponent.alignment = TextAlignmentOptions.TopRight;
	        }
	        else
	        {
		        inputMsg.gameObject.SetActive(true);
		        tmpInput.gameObject.SetActive(false);
		        inputMsg.textComponent.alignment = TextAnchor.UpperLeft;
	        }
        }
        

        #endregion

        #region UI生命周期

        private void Delay(float time, Action callback)
        {
	        StartCoroutine(OnDelaying(time, callback));
        }

        private IEnumerator OnDelaying(float time, Action callback)
        {
	        if (time > 0)
	        {
		        yield return new WaitForSeconds(time);
	        }
	        else
	        {
		        yield return null;
	        }
	        callback?.Invoke();
        }


        /// <summary>
        /// 关闭UI
        /// </summary>
        public void Close()
        {
	        Destroy(gameObject);
        }

        #endregion
        
        #region UI动画

        private void ResetRootNode()
        {
            
        }

        private Vector3 startPos;
        private void OnOpen()
        {
	        // root.PlayUIAnim(UIAnimationType.BotIn, OnFinishOpen);
	        // float time = 0.35f;
	        startPos = root.localPosition;
	        var pos = startPos;
	        pos.y -= Screen.height * 0.5f;
	        root.localPosition = pos;
	        DOTween.Sequence()
		        .Append(root.DOLocalMoveY(startPos.y + 30, 0.25f).SetEase(Ease.OutSine))
		        .Append(root.DOLocalMoveY(startPos.y, 0.25f)).Play();
        }
        
        
        private void OnClosing()
        {
	        // root.PlayUIAnim(UIAnimationType.BotOut, Close);
	        float time = 0.3f;
	        var pos = root.localPosition;
	        pos.y -= Screen.height * 0.5f;
	        root.DOLocalMoveY(pos.y, time)
		        .SetEase(Ease.InSine)
		        .OnComplete(Close);
        }



        #endregion
        
        #region 按钮响应

        /// <summary>
        /// 点击关闭按钮
        /// </summary>
        private void OnClickCloseEvent()
        {
            OnClosing();
        }
		
        /// <summary>
        /// 点击提交
        /// </summary>
        private void OnClickSubmitEvent()
        {
	        // 所有评价都会显示Thanks
	        OnSubmitAction();
	        State = RATING_STATE_THANKS;
        }

        private void OnSubmitAction()
        {
	        string msg = inputMsg.text;
	        if (_isRTL) msg = tmpInput.text;
	        _ratingCallback?.Invoke(_ratingValue, msg);
        }



        #endregion

        #region 状态控制

        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="value"></param>
        private void SetState(int value)
        {
	        nodeRating.gameObject.SetActive(false);
	        nodeLowStar.gameObject.SetActive(false);
	        nodeThanks.gameObject.SetActive(false);

	        switch (value)
	        {
		        case RATING_STATE_ENTER:
			        ShowNode(nodeRating, true);
			        break;
		        
		        case RATING_STATE_FEEDBACK:
			        // LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform)nodeLowStar.transform);
			        ShowNode(nodeLowStar, _curState == value);
			        break;
		        
		        case RATING_STATE_THANKS:
			        ShowNode(nodeThanks);
			        break;
	        }
	        
	        _curState = value;
        }

        private void RootResize(Vector2 size, float time = 0.3f)
        {
	        root.DOSizeDelta(size, time);
        }

        private void RootResize(Transform targetTrans, float time = 0.3f)
        {
	        RootResize(GetRectSize(targetTrans), time);
        }


        private Vector2 GetRectSize(Transform trans)
        {
	        var rectTrans = ((RectTransform)trans);
	        var size = new Vector2(rectTrans.rect.width, rectTrans.rect.height);
	        
	        LayoutRebuilder.ForceRebuildLayoutImmediate(rectTrans);
	        rectTrans.ForceUpdateRectTransforms();
	        LayoutGroup layoutGroup = trans.gameObject.GetComponent<LayoutGroup>();
	        if (layoutGroup != null)
	        {
		        size.x = layoutGroup.preferredWidth;
		        size.y = layoutGroup.preferredHeight;
	        }
	        
	        return size;
        }


        private void ShowNode(CanvasGroup group, bool skipAnim = false)
        {
	        float time = 0;
	        if (!skipAnim)
	        {
		        time = 0.25f;
		        group.alpha = 0;
		        group.DOFade(1, time * 2);
		        Delay(Time.deltaTime, ()=> RootResize(group.transform, time));
	        }
	        else
	        {
		        group.alpha = 1;
		        Delay(Time.deltaTime, ()=> RootResize(group.transform, 0));
	        }
	        group.gameObject.SetActive(true);
	        
        }


        #endregion

        #region 评分逻辑

        private void OnGetStarValue(int value)
        {
	        _ratingValue = value;
	        Debug.Log($"<color=#8ff00>--- get star: {value} </color>");
	        ChangeNextState();
        }

        private void ChangeNextState()
        {
	        if (State == RATING_STATE_ENTER)
	        {
		        if (_ratingValue < 5)
		        {
			        State = RATING_STATE_FEEDBACK;
			        UpdateFeedbackInfo();
			        uiStars2.Value = _ratingValue;
		        }
		        else
		        {
			        Delay(0.5f, () =>
			        {
				        State = RATING_STATE_THANKS;
				        _ratingCallback?.Invoke(5, "");
			        }); // 成功给到5星, 弹IAR评价
		        }
	        }
	        else if(State == RATING_STATE_FEEDBACK)
	        {
		        UpdateFeedbackInfo();
	        }
        }

        private void UpdateFeedbackInfo()
        {
	        string sTitle = "";
	        string sInfo = "";
	        if (_ratingValue >= 4)
	        {
		        // 更新信息显示
		        sTitle = GetLoc("k_rating_star4_title");
		        if (_isRTL)
		        {
			        sTitle = EMOJI_HAPPY + " " + sTitle;
		        }
		        else
		        {
			        sTitle += " " + EMOJI_HAPPY;   
		        }
		        sInfo = GetLoc("k_rating_star4_info");
	        }
	        else
	        {
		        // 更新信息显示
		        sTitle = GetLoc("k_rating_star3_title");
		        if (_isRTL)
		        {
			        sTitle = EMOJI_CRY + " " + sTitle;
		        }
		        else
		        {
			        sTitle += " " + EMOJI_CRY;   
		        }
		        sInfo = GetLoc("k_rating_star3_info");
	        }

	        txtLowstarTitle.text = sTitle;
	        txtLowstarInfo.text = sInfo;
	        
	        if (_ratingValue == 5)
	        {
		        State = RATING_STATE_THANKS;
		        _ratingCallback?.Invoke(5, "");
	        }
        }



        #endregion
        
        #region 多语言取值

        private string GetLoc(string key) => I2.Loc.LocalizationManager.GetTranslation(key);


        #endregion

    }
}
