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

public class BulkOrderAchievedView : MonoBehaviour
{
    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 Text heartText;
    [SerializeField] private Text coinText;
    [SerializeField] private Text bonusCoinText;
    [SerializeField] private Text messageText;
    [SerializeField] private BulkOrderCharacter bulkOrderCharacter;
    [SerializeField] private Image orderCharacterImage;

    private void Start()
    {
        if (LocalCacheManager.Load<BulkOrderData>(BulkOrder.DataTag, null) is BulkOrderData orderData)
        {
            var gameData = GameDataManager.GameData;
            var messageList = SpreadsheetDataManager.Instance.GetBaseDataList<BulkOrderTextData>(Const.BulkOrderTextDataSheet);
            var rarityList = SpreadsheetDataManager.Instance.GetBaseDataList<RarityData>(Const.RarityDataSheet);
            var bonus = BulkOrder.CalcBonus(rarityList, gameData.CompletedProductList, orderData.shopLevel);
            heartText.text = orderData.rewardHeart.ToString();
            coinText.text = orderData.rewardCoin.ToString();
            bonusCoinText.text = bonus.ToString();
            messageText.text = messageList.First(data => data.id == gameData.OrderTextId).thanksText;
            orderCharacterImage.sprite = bulkOrderCharacter.GetThanksIcon(gameData.OrderIconIndex);
        }
        closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            if (LocalCacheManager.Load<Action>(BulkOrder.AchievedCallbackTag, null) is Action callback)
            {
                callback.Invoke();
            }
            if (LocalCacheManager.Load<Action>(KitchenManager.ArchivedCallbackTag, null) is Action kitchenCallback)
            {
                kitchenCallback.Invoke();
            }
            transform.parent.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.BulkOrderAchievement);
            });
        }).AddTo(this);
    }
}
