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

public class RecipeDetailView : MonoBehaviour
{
    public static readonly string DetailRecipeTag = "RecipeData";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    

    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private Button cancelButton;
    [SerializeField] private Button nextButton;
    [SerializeField] private GameObject disabledNextButton;
    [SerializeField] private Text flavorName;
    [SerializeField] private Text flavorPrice;
    [SerializeField] private Text flavorStock;
    [SerializeField] private Text cornAmountText;
    [SerializeField] private Text flavor1AmountText;
    [SerializeField] private Text flavor2AmountText;
    [SerializeField] private GameObject flavor2View;
    private static readonly string flavorStockFormat = "所持数 :{0}";
    private static readonly string cornAmountFormat = "{0}/{1}";
    private static readonly string flavorAmountFormat = "{0} / {1}";

    private void Start()
    {
        var data = LocalCacheManager.Load<RecipeData>(DetailRecipeTag);
        
        cancelButton.OnClickAsObservable().Subscribe(_ =>
        {
            transform.parent.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.RecipeChoice);
            });
        }).AddTo(this);

        SetRecipe(data);
        if (CheckAmount(data))
        {
            disabledNextButton.SetActive(false);
            nextButton.OnClickAsObservable().Subscribe(_ =>
            {
                var gameData = GameDataManager.GameData;
                gameData.cornSeed -= data.CornAmount;
                var flavorIndex1 = gameData.Material.FindIndex(x => x.Id == data.Flavors[0].id);
                var stockMaterial1 = gameData.Material[flavorIndex1];
                stockMaterial1.Amount -= data.Flavors[0].amount;
                gameData.Material[flavorIndex1] = stockMaterial1;
                if (data.Flavors.Count == 2)
                {
                    var flavorIndex2 = gameData.Material.FindIndex(x => x.Id == data.Flavors[1].id);
                    var stockMaterial2 = gameData.Material[flavorIndex2];
                    stockMaterial2.Amount -= data.Flavors[1].amount;
                    gameData.Material[flavorIndex2] = stockMaterial2;
                }
                
                GameDataManager.SaveGameData();
                TransitionManager.Instance.LoadScene(GameScenes.Cooking);
            }).AddTo(this);
        }
        else
        {
            nextButton.interactable = false;
            disabledNextButton.SetActive(true);
        }
    }

    public void SetRecipe(RecipeData data)
    {
        var gameData = GameDataManager.GameData;
        
        // 在庫
        // 店頭の空きがない
        var shopStock = gameData.ShopStock.FindAll(x => x == data.RecipeId).Count;
        var tankStock = gameData.StorageTanks.FindAll(x => x.FlavorId == data.RecipeId).Sum(x => x.Stock);
        flavorStock.text = string.Format(flavorStockFormat, shopStock + tankStock);
        flavorName.text = data.Name;
        flavorPrice.text = data.Price.ToString();
        cornAmountText.text = string.Format(cornAmountFormat, gameData.cornSeed, data.CornAmount);

        var flavor1Amount = 0;
        var flavorIndex1 = gameData.Material.FindIndex(x => x.Id == data.Flavors[0].id);
        if (flavorIndex1 != -1)
        {
            flavor1Amount = gameData.Material[flavorIndex1].Amount;
        }
        flavor1AmountText.text = string.Format(flavorAmountFormat, flavor1Amount, data.Flavors[0].amount);
        
        var flavor2Amount = 0;
        if (data.Flavors.Count == 2)
        {
            var flavorIndex2 = gameData.Material.FindIndex(x => x.Id == data.Flavors[1].id);
            if (flavorIndex2 != -1)
            {
                flavor2Amount = gameData.Material[flavorIndex2].Amount;
            }
            flavor2View.SetActive(true);
            flavor2AmountText.text = string.Format(flavorAmountFormat, flavor2Amount, data.Flavors[1].amount);
        }
        else
        {
            flavor2View.SetActive(false);
        }
    }

    private bool CheckAmount(RecipeData data)
    {
        var flag = true;
        var gameData = GameDataManager.GameData;
        if (gameData.cornSeed < data.CornAmount)
        {
            flag = false;
            cornAmountText.color = Color.red;
        }
        var flavorIndex1 = gameData.Material.FindIndex(x => x.Id == data.Flavors[0].id);
        if (flavorIndex1 == -1 || gameData.Material[flavorIndex1].Amount < data.Flavors[0].amount)
        {
            flag = false;
            flavor1AmountText.color = Color.red;
        }
        if (data.Flavors.Count == 2)
        {
            var flavorIndex2 = gameData.Material.FindIndex(x => x.Id == data.Flavors[1].id);
            if (flavorIndex2 == -1 || gameData.Material[flavorIndex2].Amount < data.Flavors[1].amount)
            {
                flag = false;
                flavor2AmountText.color = Color.red;
            }
        }

        if (!flag)
        {
            return false;
        }
        
        // 店頭の空きがない
        // 店頭の空きに追加
        if (Market.ShopStockCount >= gameData.ShopStock.Count + data.Volume)
        {
            return true;
        }
        // 空のタンクに追加
        if (gameData.StorageTanks.FindIndex(x => x.Stock == 0) != -1)
        {
            return true;
        }
        // 同じフレーバーのタンクを確認
        var index = gameData.StorageTanks.FindIndex(x => x.FlavorId == data.RecipeId);
        if (index != -1)
        {
            // 同じフレーバーのタンクの空きに追加
            var tank = gameData.StorageTanks[index];
            if (tank.Capacity >= tank.Stock + data.Volume)
            {
                return true;
            }
        }

        return false;
    }
}