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

public class LevelCell : MonoBehaviour
{
    public Action<int> DelClick;

    public Transform CurrentSignTrans => mGobCurrent.transform;

    [SerializeField] Button mBtnBg;
    [SerializeField] ImageNum mInmLevel;
    [SerializeField] Image mImgIconBg;
    [SerializeField] Image mImgIcon;
    [SerializeField] GameObject mGobDone;
    [SerializeField] GameObject mGobComplete;
    [SerializeField] Image mImgProgress;
    [SerializeField] GameObject mGobCurrent;

    [SerializeField] GameObject mGobEmpty;
    [SerializeField] Button mBtnComingSoon;
    [SerializeField] Image mImgComingSoon;

    private int mIndex;
    private int mLevelID;
    
    private void Awake()
    {
        UIUtils.BindBtn(mBtnBg, OnClickBg);
        UIUtils.BindBtn(mBtnComingSoon, OnClickComingSoon, AudioClipType.New);
    }

    public void Init(int pIndex)
    {
        mIndex = pIndex;

        mLevelID = GameConfig.Instance.LevelSort[mIndex];
        LevelData tLvData = GameConfig.Instance.GetLevelData(mLevelID);

        mInmLevel.SetNum(mIndex + 1);
        if (ColorUtility.TryParseHtmlString(tLvData.LevelColorCode, out Color tBgColor))
        {
            mImgIconBg.color = tBgColor;
        }

        mImgIcon.sprite = ResourceManager.Instance.LoadRes<Sprite>(Const.Path.GetLevelIconSmall(mLevelID));

        int tUnlockedEndingCount = PlayerData.Instance.EndingCountOfLevel(mLevelID);
        bool tIsAllEndingsDone = tUnlockedEndingCount == tLvData.Endings.Count;
        mGobDone.SetActive(tIsAllEndingsDone);
        mGobComplete.SetActive(tIsAllEndingsDone);

        mImgProgress.fillAmount = (float)tUnlockedEndingCount / tLvData.Endings.Count;

        mBtnBg.gameObject.SetActive(true);
        mGobEmpty.SetActive(false);
        mBtnComingSoon.gameObject.SetActive(false);
    }

    public void ShowCurrent(bool pShow)
    {
        mGobCurrent.SetActive(true);//always show,only use transform
        //mGobCurrent.SetActive(pShow);
    }

    public void SetEmpty()
    {
        mBtnBg.gameObject.SetActive(false);
        mGobEmpty.SetActive(true);
        mBtnComingSoon.gameObject.SetActive(false);
    }

    public void SetComingSoon()
    {
        mBtnBg.gameObject.SetActive(false);
        mGobEmpty.SetActive(false);
        mBtnComingSoon.gameObject.SetActive(true);
    }

    private void OnClickBg()
    {
        DelClick?.Invoke(mIndex);
    }

    private void OnClickComingSoon()
    {
        mImgComingSoon.gameObject.SetActive(true);

        mImgComingSoon.color = Color.white;
        mImgComingSoon.rectTransform.localScale = Vector3.zero;

        mImgComingSoon.rectTransform.DOKill();
        mImgComingSoon.rectTransform.DOScale(1, 0.5f).SetEase(Ease.OutBounce);

        mImgComingSoon.DOKill();
        mImgComingSoon.DOFade(0, 0.5f).SetDelay(2f);
    }
}