using System;
using DG.Tweening;
using BingoBrain.Core;
using BingoBrain.HotFix;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using Spine;
using UnityEngine.UI;
namespace BingoBrain
{
    public class CardEntity
    {
        public CardData data = new CardData();
        public GameCell Game = new GameCell();
        private TextMeshPro text;
        private SpriteRenderer alphaNum;
        private GameObject selectStar;
        private GameObject coin;

        private Transform reward;

        private Tween alphaTween;

        public void InitGameObj(Action action)
        {
            if (Game.gameObject == null)
            {
                string card_name = "CardItem";
                if (GameHelper.IsGiftSwitch()) card_name = "CardItem_gift";
                Game.InitByPath("Prefab.Game.Card", card_name, () =>
                {
                    text = Game.transform.Find("num").GetComponent<TextMeshPro>();
                    selectStar = Game.transform.Find("selectStar").gameObject;
                    reward = Game.transform.Find("reward");
                    coin = Game.transform.Find("coin").gameObject;
                    alphaNum = text.transform.GetChild(0).GetComponent<SpriteRenderer>();
                    Game.transform.localScale = Vector3.one * 1.04f;
                    TriggerBingo.Get(Game.gameObject).onClick = OnClick;
                    alphaNum.color = new Color(1f, 1f, 1f, 0f);
                    action?.Invoke();
                });
            }
            else
            {
                alphaNum.color = new Color(1f, 1f, 1f, 0f);
                action?.Invoke();
            }
        }

        public void SetByData()
        {
            // alphaNum.text = text.text = GameHelper.GetNum(data.num);
            text.text = GameHelper.GetNum(data.num);
            if (data.cardBoard.data.selectList.Contains(data.index))
            {
                data.isSelect = true;
            }

            if (data.isDelaySelect)
            {
                if (!data.cardBoard.data.selectList.Contains(data.index))
                {
                    CheckReward();
                    data.cardBoard.data.selectList.Add(data.index);
                    data.isSelect = true;
                }
            }

            SetIsSelect();
        }

        public void AddToSelectedList()
        {
            data.isDelaySelect = true;
        }

        public void SetReward()
        {
            if (data.type == CardPropType.none || data.isSelect)
            {
                reward.gameObject.SetActive(false);
            }
            else
            {
                reward.gameObject.SetActive(true);
                for (int i = 0; i < reward.childCount; i++)
                {
                    reward.GetChild(i).gameObject.SetActive(i == (int)data.type);
                }
            }
        }

        public void OnReset()
        {
            alphaTween?.Pause();
            delayedCall?.Kill();
            delayedCall = null;
            alphaNum.color = new Color(1f, 1f, 1f, 0f);
            data.cardBoard.isFinish = false;
            data.cardBoard.isBingoing = false;
            data.isSelect = false;
            data.isCoin = false;
        }

        private void OnClick(PointerEventData pointerEventData)
        {
            if (!BingoCell.IsInGame)
            {
                return;
            }

            if (data.cardBoard.isFinish)
            {
                return;
            }

            if (data.cardBoard.isBingoing)
            {
                return;
            }

            if (BingoCell.isCallFinish)
            {
                return;
            }

            if (BingoCell.isGameOver)
            {
                return;
            }

            if (NNfds.IsPointerOnUI())
            {
                return;
            }

            if (data.isDelaySelect)
            {
                return;
            }

            if (BingoCell.calledList.Contains(data.num))
            {
                Audio.Instance.PlayDynamicEffect("daub");
            }
            else
            {
                Audio.Instance.PlayDynamicEffect("daub_error");
            }

            if (!data.isSelect && BingoCell.calledList.Contains(data.num))
            {
                data.isSelect = true;
                data.cardBoard.data.selectList.Add(data.index);

                CheckReward();
                SetIsSelect();
                data.cardBoard.CheckBingo();
                GameDispatcher.Instance.Dispatch(BingoInfo.SelectOneNum, this);
                if (!PreferencesMgr.Instance.IsCompleteFirstGame)
                {
                    PreferencesMgr.Instance.IsCompleteFirstGame = true;
                }

                alphaTween?.Pause();
                alphaNum.color = new Color(1f, 1f, 1f, 0f);
                var effect = Battle.Instance.ShungTik.Get("Effect.spark.fx_number_enter", "fx_number_enter");
                effect.transform.SetParent(Game.transform, false);
                DOVirtual.DelayedCall(1, () => { ReleaseEffect(effect); }).SetAutoKill();
            }
        }

        private void ReleaseEffect(GameObject effect)
        {
            Battle.Instance.ShungTik.Release(effect);
        }

        private void CheckReward()
        {
            var val = GetSumToType(data.type);
            var startPot = GameHelper.WoldToUIPot(Game.transform.position);
            var rewardData = new RewardData
            {
                displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange
            };
            var rewardSingleData = new Goda(101, val, RewardOrigin.Play)
            {
                startPosition = startPot
            };

            switch (data.type)
            {
                case CardPropType.coin:
                    rewardSingleData.id = 101;
                    rewardData.AddReward(rewardSingleData);
                    GameDispatcher.Instance.Dispatch(BingoInfo.GetReward, rewardData);

                    break;
                case CardPropType.coinx3:
                    rewardSingleData.id = 101;
                    rewardData.AddReward(rewardSingleData);
                    GameDispatcher.Instance.Dispatch(BingoInfo.GetReward, rewardData);
                    break;
                case CardPropType.cash:

                    rewardSingleData.id = 102;
                    rewardData.AddReward(rewardSingleData);
                    if (GameHelper.IsGiftSwitch()) UICtrlDispatcher.Instance.Dispatch(SkinInfo.StarRewardUI_Open);
                    else GameDispatcher.Instance.Dispatch(BingoInfo.GetReward, rewardData);
                    break;
                case CardPropType.cashx3:
                    rewardSingleData.id = 102;
                    rewardData.AddReward(rewardSingleData);
                    if (GameHelper.IsGiftSwitch()) UICtrlDispatcher.Instance.Dispatch(SkinInfo.StarRewardUI_Open, true);
                    else GameDispatcher.Instance.Dispatch(BingoInfo.GetReward, rewardData);
                    break;
                case CardPropType.fanpai:
                    BingoCell.AddKeyCardSum(1);
                    break;
            }
        }

        public static decimal GetSumToType(CardPropType type)
        {
            var coinVO = GameHelper.GetDynamicVersion_Coin();
            var cashVO = GameHelper.GetDynamicVersion_Cash();
            switch (type)
            {
                case CardPropType.coin:
                    return coinVO.coinRange[0];
                case CardPropType.coinx3:
                    return coinVO.coinRange[1];
                case CardPropType.cash:
                    {
                        var sum = (int)((cashVO.cashRange[1] - cashVO.cashRange[0]) / cashVO.range);
                        return (decimal)(cashVO.cashRange[0] + (UnityEngine.Random.Range(0, sum + 1) * cashVO.range));
                    }
                case CardPropType.cashx3:
                    {
                        var sum = (int)((cashVO.cashRange2[1] - cashVO.cashRange2[0]) / cashVO.range);
                        return (decimal)(cashVO.cashRange2[0] + (UnityEngine.Random.Range(0, sum + 1) * cashVO.range));
                    }
                default:
                    return 100;
            }
        }

        private float tweenTime = 0.5f;
        private Tween delayedCall;

        public void TweenAlphaNum()
        {
            delayedCall = DOVirtual.DelayedCall((float)GameHelper.GetCommonModel().hintDelayTime, () =>
            {
                delayedCall = null;
                if (data.isSelect)
                {
                    return;
                }

                alphaTween ??= alphaNum.DOFade(1, tweenTime).SetLoops(-1, LoopType.Yoyo);

                alphaTween.Restart();
            });
        }

        void SetIsSelect()
        {
            text.gameObject.SetActive(!data.isSelect);
            selectStar.SetActive(data.isSelect);
            coin.SetActive(false);
            reward.gameObject.SetActive(false);
        }

        public void SetCoin(float time = 0.2f)
        {
            data.isCoin = true;
            selectStar.SetActive(false);
            coin.SetActive(true);
            text.gameObject.SetActive(false);

            coin.transform.DOScale(1.2f, time / 2).SetLoops(2, LoopType.Yoyo);
        }
    }
}