using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using MyGame.Scripts;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class RecipeSelectDialog : MonoBehaviour
{
    private static readonly string CallbackTag = "RecipeSelectDialogCallback";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private ScrollRect scrollRect;
    [SerializeField] private RecipeView recipePrefab;
    [SerializeField] private Button closeButton;
    // Start is called before the first frame update
    void Start()
    {
        var gameData = GameDataManager.GameData;
        closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                LocalCacheManager.Load<Action>(CallbackTag, null)?.Invoke();
                TransitionManager.Instance.UnloadScene(GameScenes.Recipe); 
            });
        }).AddTo(this);
        
        // レシピ一覧生成
        var content = scrollRect.content;
        content.transform.DestroyAllChildrens();
        var productDataList = SpreadsheetDataManager.Instance.GetBaseDataList<ProductData>(Const.ProductDataSheet);
        var shopDataList = SpreadsheetDataManager.Instance.GetBaseDataList<ShopData>(Const.ShopDataSheet);
        var ownedRecipesList = shopDataList.Where(data => data.Category == ItemCategory.Recipe).Select(data => data.itemId).ToList();
        var targetList = productDataList
            .Where(data => data.shopLevel != Const.SpecialShopLevel || ownedRecipesList.Contains(data.id))
            .OrderByDescending(data => gameData.MyRecipes.Contains(data.id))
            .ThenBy(data => ownedRecipesList.Contains(data.id))
            .ToList();
        
        foreach (var productData in targetList)
        {
            var view = Instantiate(recipePrefab, content.transform);
            view.SetRecipe(productData);
            // 所持レシピ確認
            if (gameData.MyRecipes.Contains(productData.id))
            {
                view.SetLockPanel(false);
                view.RecipeClickObservable.ThrottleFirst(TimeSpan.FromSeconds(.3f)).Subscribe(_ =>
                {
                    LocalCacheManager.Save(PopcornGameManager.CookingDataTag, productData);
                    RecipeDetailView.ShowDialog();
                }).AddTo(this);
            }
            else
            {
                view.SetLockPanel(true);
            }
        }
        LayoutRebuilder.ForceRebuildLayoutImmediate(content);
        scrollRect.verticalNormalizedPosition = 1;
        
        if (!gameData.FinishedFlags.HasFlag(TutorialFlag.FirstPlay))
        {
            scrollRect.vertical = false;
            // マスク表示
            var view = content.GetChild(0).GetComponent<RecipeView>();
            var viewRectTransform = view.transform.GetChild(0) as RectTransform;
            var go = TutorialManager.Instance.ShowTutorialMask(transform.parent, viewRectTransform);
            view.RecipeClickObservable.Take(1).Subscribe(_ =>
            {
                DestroyImmediate(go);
            }).AddTo(this);
        }
    }

    public static void ShowDialog(ProductViewType type, Action onClose = null)
    {
        LocalCacheManager.Save(Const.ProductViewTypeTag, type);
        LocalCacheManager.Save(CallbackTag, onClose);
        TransitionManager.Instance.LoadSceneAdditive(GameScenes.Recipe);
    }
}
