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

public class BulkOrderAchievedView : MonoBehaviour
{
    private static readonly string CallbackTag = "BulkOrderAchievedViewCallback";
    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;
    
    // effect用
    [SerializeField] private Transform heartIconTransform;
    [SerializeField] private Transform coinIconTransform;

    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.rewardHeart);
            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(_ =>
        {
            LocalCacheManager.Load<Action<Vector3, Vector3>>(CallbackTag, null)?.Invoke(coinIconTransform.position, heartIconTransform.position);
            LocalCacheManager.Remove(CallbackTag);
            transform.parent.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.BulkOrderAchievement);
            });
        }).AddTo(this);
    }

    public static void ShowDialog(Action<Vector3, Vector3> onComplete = null)
    {
        LocalCacheManager.Save(CallbackTag, onComplete);
        TransitionManager.Instance.LoadSceneAdditive(GameScenes.BulkOrderAchievement);
    }
}
