using System;
using MyGame.Scripts;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class ShopItemPurchaseView : MonoBehaviour
{
    private static readonly string ItemPurchaseTag = "ItemPurcahse";
    private static readonly string PurchaseCallbackTag = "ShopItemPurchaseViewPurchaseCallbackTag";
    private static readonly string CloseCallbackTag = "ShopItemPurchaseViewCloseCallbackTag";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    private static readonly int MaxPurchaseCount = 999;
    private static readonly int MinPurchaseCount = 1;
    
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private Text name;
    [SerializeField] private Transform iconTarget;
    [SerializeField] private Text price;
    [SerializeField] private Text text;
    [SerializeField] private Text stockCount;
    [SerializeField] private Text totalPrice;
    [SerializeField] private Text purchaseCount;
    [SerializeField] private Button subCountButton;
    [SerializeField] private Button addCountButton;
    [SerializeField] private Button closeButton;
    [SerializeField] private Button purchaseOnButton;
    [SerializeField] private GameObject purchaseOffButton;
    [SerializeField] private GameObject quantitySelectObject;
    [SerializeField] private GameObject explanationObject;
    [SerializeField] private GameObject stockCountObject;

    private Color redColor;
    private Color defaultColor;
    private readonly IntReactiveProperty currentCount = new IntReactiveProperty();
    private void Start()
    {
        currentCount.AddTo(this);
        defaultColor = totalPrice.color;
        ColorUtility.TryParseHtmlString(Const.RedColorString, out redColor);
        // 表示データを受け取る
        var data = LocalCacheManager.Load<(ShopData shopData, int stockCount)>(ItemPurchaseTag);
        LocalCacheManager.Remove(ItemPurchaseTag);
        SetData(data.shopData, data.stockCount);
        closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            LocalCacheManager.Load<Action>(CloseCallbackTag, null)?.Invoke();
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.Purchase);
            });
        }).AddTo(this);
        purchaseOnButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            purchaseOnButton.interactable = false;
            LocalCacheManager.Load<Action<int>>(PurchaseCallbackTag, null)?.Invoke(currentCount.Value);
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.Purchase);
            });
        }).AddTo(this);

        currentCount.Value = MinPurchaseCount;
        currentCount.Subscribe(x =>
        {
            var total = data.shopData.price * x;
            SetButtonActive(total <= CoinManager.Instance.OwnCoin);
            totalPrice.color = total <= CoinManager.Instance.OwnCoin ? defaultColor : redColor;
            totalPrice.text = $"{total}";
            purchaseCount.text = $"{x}";
        }).AddTo(this);
        stockCountObject.SetActive(data.shopData.ConsumeType == ShopItemType.Consumable);
        quantitySelectObject.SetActive(data.shopData.ConsumeType == ShopItemType.Consumable);
        explanationObject.SetActive(data.shopData.ConsumeType == ShopItemType.NonConsumable);
        if (data.shopData.ConsumeType == ShopItemType.Consumable)
        {
            addCountButton.OnClickAsObservable().Select(_ => 1)
                .Merge(subCountButton.OnClickAsObservable().Select(_ => -1))
                .Subscribe(x =>
                {
                    currentCount.Value = Mathf.Clamp(currentCount.Value + x, MinPurchaseCount, MaxPurchaseCount);
                }).AddTo(this);
        }
        else
        {
            currentCount.Value = 1;
        }
        
        if (GameDataManager.GameData.isFirstPlay)
        {
            // マスク表示
            var go = TutorialManager.Instance.ShowTutorialMask(transform.parent, purchaseOnButton.transform as RectTransform);
            purchaseOnButton.OnClickAsObservable().Take(1).Subscribe(_ =>
            {
                DestroyImmediate(go);
            }).AddTo(this);
        }
    }

    private void SetData(ShopData shopData, int count)
    {
        name.text = shopData.name;
        price.text = $"{shopData.price}";
        stockCount.text = $"所持数 :{count}";
        text.text = shopData.text;
        iconTarget.DestroyAllChildrens();
        Instantiate(shopData.GetPrefab(), iconTarget);
    }

    private void SetButtonActive(bool active)
    {
        purchaseOnButton.gameObject.SetActive(active);
        purchaseOffButton.SetActive(!active);
    }

    public static void ShowDialog((ShopData shopData, int stockCount) data, Action<int> onPurchase, Action onClose = null)
    {
        LocalCacheManager.Save(ItemPurchaseTag, data);
        LocalCacheManager.Save(PurchaseCallbackTag, onPurchase);
        LocalCacheManager.Save(CloseCallbackTag, onClose);
        TransitionManager.Instance.LoadSceneAdditive(GameScenes.Purchase);
    }
}
