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

namespace MyGame.Scenes.Main.Scripts
{
    public class AutoCookCaution : MonoBehaviour
    {
        private static readonly string CallbackTag = "UpdateDialogCallback";
        public static readonly string AutoCookCompleteProductsTag = "AutoCookCompleteProducts";
        private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
        private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");

        [SerializeField] private Animator backgroundAnimator;
        [SerializeField] private Button closeButton;
        [SerializeField] private Button getButton;

        [SerializeField] private AutoCookPopcornView[] popcorns;

        private void Start()
        {
            var (earnList, discardList) = LocalCacheManager.Load<(IReadOnlyList<ProductData>, IReadOnlyList<ProductData>)>(AutoCookCompleteProductsTag);
            var gameData = GameDataManager.GameData;
            var autoCookDataList = SpreadsheetDataManager.Instance.GetBaseDataList<AutoCookData>(Const.AutoCookDataSheet);
            var autoCookData = autoCookDataList.First(data => data.level == gameData.AutoCookLevel);
            
            closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
            {
                LocalCacheManager.Remove(CallbackTag);
                TransitionManager.Instance.LoadScene(GameScenes.ProductManagement);
            }).AddTo(this);
            getButton.OnClickAsObservable().Take(1).Subscribe(_ =>
            {
                // コーン獲得
                foreach (var productData in earnList.Where(data => !discardList.Contains(data)))
                {
                    CookingResult.AddStock(productData);
                }
                    
                // 自動調理セーブ
                gameData.AutoCookProducts = Array.Empty<int>();
                var maxLevel = autoCookDataList.Last().level;
                if (gameData.AutoCookLevel < maxLevel)
                {
                    gameData.AutoCookUsesCount++;
                    if (gameData.AutoCookUsesCount >= autoCookData.clearCount)
                    {
                        gameData.AutoCookUsesCount = 0;
                        gameData.AutoCookLevel++;
                    }
                }
                GameDataManager.SaveGameData();
                
                LocalCacheManager.Load<Action>(CallbackTag, null)?.Invoke();
                LocalCacheManager.Remove(CallbackTag);
                transform.parent.SetLocalScale(0);
                backgroundAnimator.SetTrigger(CloseTrigger);
                this.CallWaitForSeconds(.25f, () =>
                {
                    TransitionManager.Instance.UnloadScene(GameScenes.AutomaticCookingCaution);
                });
            }).AddTo(this);
            
            // 完成したポップコーンを表示
            var productCount = discardList.Count;
            for (int i = 0; i < popcorns.Length; i++)
            { 
                if (i < productCount)
                {
                    popcorns[i].SetView(discardList[i], true);
                    popcorns[i].SetActive(true);
                }
                else
                {
                    popcorns[i].SetActive(false);
                }
            }

            // 描画計算
            var rebuildTarget = popcorns[0].transform.parent.parent;
            var originalScale = rebuildTarget.localScale;
            rebuildTarget.localScale = Vector3.zero;
            Observable.TimerFrame(0, FrameCountType.EndOfFrame).Subscribe(_ =>
            {
                LayoutRebuilder.ForceRebuildLayoutImmediate(rebuildTarget as RectTransform);
                rebuildTarget.localScale = originalScale;
            }).AddTo(this);
        }
        
        public static void ShowDialog((IReadOnlyList<ProductData> earnList, IReadOnlyList<ProductData> discardList) products, Action onClose = null){
            LocalCacheManager.Save(AutoCookCompleteProductsTag, products);
            LocalCacheManager.Save(CallbackTag, onClose);
            TransitionManager.Instance.LoadSceneAdditive(GameScenes.AutomaticCookingCaution);
        }
    }
}