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

public class ShopItemView : MonoBehaviour
{
    [SerializeField] private Button detailButton;
    [SerializeField] private ShopItemPurchaseButton purchaseButton;
    [SerializeField] private Transform iconTarget;
    [SerializeField] private Text itemName;
    [SerializeField] private Text price;
    [SerializeField] private Text stockCount;
    [SerializeField] private GameObject purchaseObject;
    [SerializeField] private GameObject exchangeObject;

    private static readonly string ProgressFormat = "{0} / {1}";
    [SerializeField] private Slider progressBar;
    [SerializeField] private TextMeshProUGUI progressText;
    [SerializeField] private GameObject onObject;
    [SerializeField] private GameObject offObject;
    [SerializeField] private GameObject soldOutObject;
    [SerializeField] private Button exchangeButton;

    public IObservable<Unit> DetailButtonObservable => detailButton.OnClickAsObservable().TakeUntilDestroy(this);
    public IObservable<Unit> PurchaseButtonObservable => purchaseButton.ClickObservable;
    public IObservable<Unit> ExchangeButtonObservable => exchangeButton.OnClickAsObservable().TakeUntilDestroy(this);

    public void SetData(ShopData shopData)
    {
        itemName.text = shopData.Name;
        price.text = $"{shopData.price}";
        if (shopData.ConsumeType == ShopItemType.NonConsumable)
        {
            stockCount.transform.parent.gameObject.SetActive(false);
        }
        iconTarget.DestroyAllChildrens();
        Instantiate(shopData.GetPrefab(), iconTarget);
        purchaseButton.SetItemType(shopData.Category, shopData.ConsumeType);
        
        /*
         * レシピは広告視聴回数で開放
         * 別途フラグで切替も検討
         */
        purchaseObject.SetActive(shopData.Category != ItemCategory.Recipe);
        exchangeObject.SetActive(shopData.Category == ItemCategory.Recipe);
        progressBar.value = Mathf.InverseLerp(0, shopData.price, GameDataManager.GameData.adCount);
        progressText.text = string.Format(ProgressFormat, GameDataManager.GameData.adCount, shopData.price);
        onObject.SetActive(shopData.price <= GameDataManager.GameData.adCount);
        offObject.SetActive(!onObject.activeSelf);
    }

    public void SetStockCount(int stock)
    {
        stockCount.text = $"{stock}";
        purchaseButton.SetItemPurchased(stock > 0);
        soldOutObject.SetActive(stock > 0);
        if (soldOutObject.activeSelf)
        {
            onObject.SetActive(false);
            offObject.SetActive(false);
        }
    }

    public void SetItemActive(bool active)
    {
        purchaseButton.SetButtonActive(active);
    }
}
