using System;
using System.Linq;
using I2.Loc;
using MyGame.Scripts;
using UniRx;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;

namespace MyGame.Scenes.Main.Scripts
{
    public class AutoCookDialog : MonoBehaviour
    {
        private static readonly string SuccessCallbackTag = "AutoCookDialogSuccessCallback";
        private static readonly string CloseCallbackTag = "AutoCookDialogCloseCallback";
        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 movieButton;
        
        [SerializeField] private Text cookerLevelText;
        [SerializeField] private Text earnCountText;
        [SerializeField] private Text durationText;
        [SerializeField] private Text usesCountText;

        private void Start()
        {
            var gameData = GameDataManager.GameData;
            var autoCookDataList = SpreadsheetDataManager.Instance.GetBaseDataList<AutoCookData>(Const.AutoCookDataSheet);
            var autoCookData = autoCookDataList.First(data => data.level == gameData.AutoCookLevel);
            var maxLevel = autoCookDataList.Last().level;
            var isMaxLevel = autoCookData.level >= maxLevel;
            
            closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
            {
                LocalCacheManager.Load<Action>(CloseCallbackTag, null)?.Invoke();
                LocalCacheManager.Remove(CloseCallbackTag);
                transform.parent.SetLocalScale(0);
                backgroundAnimator.SetTrigger(CloseTrigger);
                this.CallWaitForSeconds(.25f, () =>
                {
                    TransitionManager.Instance.UnloadScene(GameScenes.AutomaticCookingMovie);
                });
            }).AddTo(this);
            movieButton.OnClickAsObservable().Take(1).Subscribe(_ =>
            {
                GetRewardDialog.ShowRewardVideo(GameScenes.AutomaticCookingMovie, AdManager.AD_PLACEMENT_AUTO, () =>
                {
                    // 自動調理開始
                    gameData.AutoCookFinishTime = DateTime.UtcNow.AddHours(autoCookData.duration).ToBinary();
                    // レシピをランダムに並び替えて保存
                    gameData.AutoCookProducts = gameData.MyRecipes.OrderBy(x => Random.value).ToArray();
                    gameData.AddUseAutoCook();
                    GameDataManager.SaveGameData();
                    LocalCacheManager.Load<Action>(SuccessCallbackTag, null)?.Invoke();
                    LocalCacheManager.Remove(SuccessCallbackTag);
                });
            }).AddTo(this);
            
            cookerLevelText.text = isMaxLevel ? "MAX" : $"{gameData.AutoCookLevel}";
            earnCountText.text = $"{autoCookData.earnCount}{ScriptLocalization.Unit.Amount}";
            durationText.text = $"{autoCookData.duration}{ScriptLocalization.Unit.Hours}";
            usesCountText.text = isMaxLevel ? "--/--" : $"{gameData.AutoCookUsesCount}/{autoCookData.clearCount}";
        }

        public static void ShowDialog(Action onSuccess = null, Action onClose = null){
            LocalCacheManager.Save(SuccessCallbackTag, onSuccess);
            LocalCacheManager.Save(CloseCallbackTag, onClose);
            TransitionManager.Instance.LoadSceneAdditive(GameScenes.AutomaticCookingMovie);
        }
    }
}