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

public class ShopItemPurchaseView : MonoBehaviour
{
    public static readonly string ItemPurchaseTag = "ItemPurcahse";
    private static readonly string redColorString= "#fb6346";
    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 icon;
    [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(redColorString, out redColor);
        // 表示データを受け取る
        var data = LocalCacheManager.Load<(ShopData shopData, int stockCount, Action<int> callback)>(ItemPurchaseTag);
        LocalCacheManager.Remove(ItemPurchaseTag);
        SetData(data.shopData, data.stockCount);
        closeButton.OnClickAsObservable().Subscribe(_ =>
        {
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.Purchase);
            });
        }).AddTo(this);
        purchaseOnButton.OnClickAsObservable().Subscribe(_ =>
        {
            data.callback.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;
        }
    }

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

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