using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

namespace DuckHunter
{
    public class GameUI : MonoBehaviour
    {
        [SerializeField] Text textScore;
        [SerializeField] Text textScoreBest;
        [SerializeField] Text textHitScore;
        [SerializeField] Button btnReset;
        [SerializeField] Button btnAim;
        [SerializeField] Button btnBack;
        [SerializeField] RectTransform duckForGameStart;
        [SerializeField] GameObject textGameOver;
        [SerializeField] GameObject textGameCompleted;
        [SerializeField] GameObject bottomBox;
        [SerializeField] Slider levelSlider;

        public static GameUI Instance;

        void Awake()
        {
            Instance = this;
            btnReset.onClick.AddListener(() =>
            {
                AudioManager.Instance.PlayBtn();
                UnityEngine.SceneManagement.SceneManager.LoadScene("DuckHunter");
            });
            btnAim.onClick.AddListener(() =>
            {
                if (btnAim.GetComponent<LongPressMonitor>().isLongPress) return;
                AudioManager.Instance.PlayBtn();
                SmartBowController.Instance.ResetAim();
            });
            btnAim.gameObject.AddComponent<LongPressMonitor>().onLongPress += () => 
            {
                AudioManager.Instance.PlayBtn();
                if (SB_EventSystem.ins) SB_EventSystem.ins.AwakenSimulateMouse(); 
            };
            btnBack.onClick.AddListener(() => {
                AudioManager.Instance.PlayBtn();
                // UnityEngine.SceneManagement.SceneManager.LoadScene("Home", UnityEngine.SceneManagement.LoadSceneMode.Single);

                //结束游戏页面
                UnityEngine.SceneManagement.SceneManager.LoadScene("Home", UnityEngine.SceneManagement.LoadSceneMode.Single);
            });
            InitLevelSlider();
            levelSlider.onValueChanged.AddListener(OnLevelSliderUpdate);
        }

        void OnDestroy()
        {
            if (Instance == this) Instance = null;
            DOTween.KillAll(false);
        }

        // Update is called once per frame
        void Update()
        {
            GameManager gm = GameManager.Instance;
            if (!gm) return;

            // int t = (int)(Time.time - startTime);
            // int m = t / 60;
            // int s = t % 60;
            // string mStr = m < 10 ? "0" + m : m.ToString();
            // string sStr = s < 10 ? "0" + s : s.ToString();
            // textTime.text = $"{mStr}:{sStr}";
        }

        void InitLevelSlider()
        {
            RenderLevelSliderText();
            levelSlider.SetValueWithoutNotify(GameManager.Instance.level);
        }
        void OnLevelSliderUpdate(float v)
        {
            GameManager.DefaultLevel = GameManager.Instance.level = (int)v;
            RenderLevelSliderText();
        }
        void RenderLevelSliderText()
        {
            var tal2 = levelSlider.transform.Find("Text").GetComponent<TextAutoLanguage2>();
            tal2.textFormatArgs = new object[] { GameManager.Instance.level };
            tal2.ApplyToText();
        }

        int _renderHitScore = 0;
        Tween _sequenceRenderHitScore;
        public void RenderHitScore(int score, int bestScore)
        {
            if (!GameManager.Instance) return;
            if (_sequenceRenderHitScore != null)
            {
                _sequenceRenderHitScore.Kill();
                _sequenceRenderHitScore = null;
            }
            _sequenceRenderHitScore = DOTween.To(() => _renderHitScore, v =>
            {
                _renderHitScore = v;
                textScore.text = _renderHitScore.ToString();
            }, score, 0.5f);
            if (bestScore > 0)
            {
                textScoreBest.gameObject.SetActive(true);
                var tal2 = textScoreBest.GetComponent<TextAutoLanguage2>();
                tal2.textFormatArgs = new object[] { bestScore };
                tal2.ApplyToText();
            }
        }

        public bool CheckHitDuckForGameStart(Vector2 screenPosition)
        {
            return RectTransformUtility.RectangleContainsScreenPoint(duckForGameStart, screenPosition);
        }

        public void HandleGameStart(System.Action callback, bool startImmediate)
        {
            if (startImmediate) TextGameScreenCenter.Instance.ShowText(TextGameScreenCenter.TextName.GAME_START_HIDE);
            else TextGameScreenCenter.Instance.ShowText(TextGameScreenCenter.TextName.GAME_START_FADEOUT);
            TweenCallback cb = () =>
            {
                bottomBox.SetActive(true);
                duckForGameStart.gameObject.SetActive(false);
                levelSlider.gameObject.SetActive(false);
                callback?.Invoke();
            };
            if (startImmediate) cb.Invoke();
            else
            {
                Sequence sequence = DOTween.Sequence();
                sequence.Append(duckForGameStart.transform.DOMoveX(Screen.width * 1.125f, 1f));
                sequence.AppendCallback(cb);
            }
        }

        List<Sequence> arrowsFadeSeqList = new List<Sequence>();
        [SerializeField] RectTransform arrowsRTF;
        public void RenderArrowCount(int count)
        {
            if (count == 0 && arrowsFadeSeqList.Count > 0) return;
            if (arrowsFadeSeqList.Count > 0)
            {
                for (int i = arrowsFadeSeqList.Count - 1; i >= 0; i--)
                {
                    var seq = arrowsFadeSeqList[i];
                    arrowsFadeSeqList.RemoveAt(i);
                    seq.Kill();
                }
            }
            for (int i = 1; i < arrowsRTF.childCount; i++)
            {
                RectTransform iconRTF = arrowsRTF.GetChild(i) as RectTransform;
                Image iconIMG = iconRTF.GetComponent<Image>();
                iconIMG.color = Color.white;
                iconRTF.gameObject.SetActive(i <= count);
                if (count == 0)
                {
                    if (i <= 3) iconRTF.gameObject.SetActive(true);
                    var seq = DOTween.Sequence();
                    arrowsFadeSeqList.Add(seq);
                    seq.Append(iconIMG.DOFade(0.5f, 0.2f));
                    seq.Append(iconIMG.DOFade(1f, 0f));
                    seq.SetLoops(-1);
                }
            }
        }

        [SerializeField] RectTransform duckCountRTF;
        int _renderHitDuckCount = 0;
        List<Sequence> _duckIconListSequences = new List<Sequence>();
        /// <summary>
        /// 渲染鸭子的状态图标列表
        /// </summary>
        public void RenderHitDuckCount(int duckType)
        {
            if (duckType > 0)
            {
                _renderHitDuckCount++;
                RectTransform iconRTF = duckCountRTF.GetChild(_renderHitDuckCount) as RectTransform;
                Image iconIMG = iconRTF.GetComponent<Image>();
                iconIMG.sprite = Resources.Load<Sprite>("DuckHunter/Textures/Icons/Duck" + duckType);
            }
            else if (duckType == 0)
            {
                _renderHitDuckCount++;
                RectTransform iconRTF = duckCountRTF.GetChild(_renderHitDuckCount) as RectTransform;
                Image iconIMG = iconRTF.GetComponent<Image>();
                var seq = DOTween.Sequence();
                _duckIconListSequences.ForEach(e => e.Restart());
                _duckIconListSequences.Add(seq);
                seq.AppendCallback(() =>
                {
                    Color c = iconIMG.color;
                    c.a = 1;
                    iconIMG.color = c;
                });
                seq.Append(iconIMG.DOFade(0.2f, 0.2f));
                seq.Append(iconIMG.DOFade(1f, 0f));
                seq.SetLoops(-1);
            }
            else
            {
                _duckIconListSequences.ForEach(e => e.Kill());
                for (int i = 1; i < duckCountRTF.childCount; i++)
                {
                    RectTransform iconRTF = duckCountRTF.GetChild(i) as RectTransform;
                    Image iconIMG = iconRTF.GetComponent<Image>();
                    var seq = DOTween.Sequence();
                    Color c = iconIMG.color;
                    c.a = 1;
                    iconIMG.color = c;
                    seq.Append(iconIMG.DOFade(0.5f, 0.2f));
                    seq.Append(iconIMG.DOFade(1f, 0f));
                    seq.SetLoops(-1);
                }
            }
        }

        Sequence _sequenceShowTextHitScore;
        public void ShowTextHitScore(int score, Vector2 screenPosition)
        {
            if (_sequenceShowTextHitScore != null)
            {
                _sequenceShowTextHitScore.Kill();
                _sequenceShowTextHitScore = null;
            }
            textHitScore.gameObject.SetActive(true);
            textHitScore.text = score.ToString();
            textHitScore.transform.position = screenPosition;
            _sequenceShowTextHitScore = DOTween.Sequence();
            _sequenceShowTextHitScore.Append(textHitScore.DOFade(0.8f, 0));
            float lpy = textHitScore.transform.localPosition.y;
            _sequenceShowTextHitScore.Append(textHitScore.transform.DOLocalMoveY(lpy + 100, 0.5f));
            _sequenceShowTextHitScore.AppendInterval(1.5f);
            _sequenceShowTextHitScore.Append(textHitScore.DOFade(0, 0.5f));
            _sequenceShowTextHitScore.AppendCallback(() => textHitScore.gameObject.SetActive(false));
        }

        [SerializeField] Text textLevel;
        public void RenderLevel(int level)
        {
            var tal2 = textLevel.GetComponent<TextAutoLanguage2>();
            tal2.textFormatArgs = new object[] { level };
            tal2.ApplyToText();
        }

        [SerializeField] RectTransform arrowBox;
        public void AddArrowOnScreen(Vector2 screenPosition)
        {
            var o = Instantiate(arrowBox.GetChild(0).gameObject, arrowBox);
            var tf = o.transform;
            tf.position = screenPosition;
            tf.gameObject.SetActive(true);
            Image img = tf.GetComponent<Image>();
            Sequence seq = DOTween.Sequence();
            seq.AppendInterval(2.5f);
            seq.Append(img.DOFade(0, 0.5f));
            seq.AppendCallback(() => Destroy(o));
        }
    }
}

