using System;
using System.Collections.Generic;
using System.Linq;
using MyGame.Scenes.Main.Scripts;
using TMPro;
using UniRx;
using UnityEngine;
using UnityEngine.PlayerLoop;
using UnityEngine.UI;
using GameAnalyticsSDK;

public class ShopLevelUp : MonoBehaviour
{
    private static readonly string DataTag = "ShopLevelUpData";
    private static readonly string CallbackTag = "ShopLevelUpCallback";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private TextMeshProUGUI shopLevelText;
    [SerializeField] private Text achievementText;
    [SerializeField] private Text recipeNameText;
    [SerializeField] private Button closeButton;
    [SerializeField] private GameObject summaryObject;

    private int shopLevel;

    private void Start()
    {
        shopLevel = LocalCacheManager.Load<int>(DataTag);
        var scriptList = SpreadsheetDataManager.Instance.GetBaseDataList<BrotherScriptData>(Const.ScriptDataSheet);
        var targetScriptList = scriptList.Where(data => data.id == shopLevel).ToList();
        var productList = SpreadsheetDataManager.Instance.GetBaseDataList<ProductData>(Const.ProductDataSheet);
        var shopLevelList = SpreadsheetDataManager.Instance.GetBaseDataList<ShopLevelData>(Const.ShopLevelDataSheet);
        var productData = productList.FirstOrDefault(data => data.shopLevel == shopLevel);
        shopLevelText.text = shopLevel.ToString();
        achievementText.text = shopLevelList.FirstOrDefault(data => data.shopLevel == shopLevel)?.Achievement ?? "";
        recipeNameText.text = productData?.Name ?? "";
        
        GameDataManager.GameData.ViewedShopLevel = shopLevel;
        GameDataManager.GameData.OrderConditionCount = 0;
        // レシピ開放
        if (productData != null)
        {
            GameDataManager.GameData.MyRecipes = new List<int>(GameDataManager.GameData.MyRecipes){productData.id}.Distinct().ToArray();
            GameDataManager.GameData.DailyRecipeGetCount++;
        }
        GameDataManager.SaveGameData();
        HeartMeter.Instance.SetShopLevel(GameDataManager.GameData.ViewedShopLevel, true);
        
        closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.StoreLevel);
                if (targetScriptList.Count > 0)
                {
                    LocalCacheManager.Save(BrotherConversation.ScriptDataTag, targetScriptList);
                    LocalCacheManager.Save(BrotherConversation.CallbackTag, new Action(() =>
                    {
                        OnClose();
                    }));
                    TransitionManager.Instance.LoadSceneAdditive(GameScenes.Conversation);
                }
                else
                {
                    OnClose();
                }
            });
        }).AddTo(this);

        summaryObject.SetActive(false);
        this.CallWaitForSeconds(1f, () =>
        {
            summaryObject.SetActive(true);
        });
    }

    private void OnClose()
    {
        // 店舗レベル15以降実装後不要になる処理
        if (shopLevel == Const.MaxShopLevel)
        {
            UpdateDialog.ShowDialog(() =>
            {
                LocalCacheManager.Load<Action>(CallbackTag, null)?.Invoke();
                LocalCacheManager.Remove(CallbackTag);
            });
        }
        else
        {
            LocalCacheManager.Load<Action>(CallbackTag, null)?.Invoke();
            LocalCacheManager.Remove(CallbackTag);
        }
#if !DEVELOPMENT_BUILD && !UNITY_EDITOR 
        // 進捗計測
        var progress = "level_" + String.Format("{0:00}", shopLevel);
        TimeSpan interval = DateTime.UtcNow - DateTime.FromBinary(GameDataManager.GameData.beginPlayTime);
        GameAnalytics.NewProgressionEvent(GAProgressionStatus.Complete, progress, (int)interval.TotalMinutes);
#endif        
    }

    public static void ShowDialog(int level, Action onComplete = null)
    {
        LocalCacheManager.Save(DataTag, level);
        LocalCacheManager.Save(CallbackTag, onComplete);
        TransitionManager.Instance.LoadSceneAdditive(GameScenes.StoreLevel);
    }
}
