using System;
using System.Linq;
using I2.Loc;
using TMPro;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class CornFieldReinforcementDetailView : MonoBehaviour
{
    private static readonly string harvestedTextFormat = "{0}";
    private static readonly string SigbBoardFormat = "x{0}";
    private static readonly int OpenTrigger = Animator.StringToHash("OpenTrigger");
    private static readonly int CloseTrigger = Animator.StringToHash("CloseTrigger");
    
    [SerializeField] private Animator backgroundAnimator;
    [SerializeField] private Button purchaseButton;
    [SerializeField] private Button releaseButton;
    [SerializeField] private Button closeButton;
    [SerializeField] private GameObject reinforceObject;
    [SerializeField] private GameObject releaseObject;
    [SerializeField] private GameObject machineObject;
    [SerializeField] private ReinforcementSeedlingView currentSeedling;
    [SerializeField] private ReinforcementSeedlingView nextSeedling;
    [SerializeField] private TextMeshProUGUI currentSignBoard;
    [SerializeField] private TextMeshProUGUI nextSignBoard;
    [SerializeField] private Text reinforcePriceText;
    [SerializeField] private Text releasePriceText;
    [SerializeField] private Transform currentMachineImage;
    [SerializeField] private Transform nextMachineImage;
    [SerializeField] private Text currentHarvestedText;
    [SerializeField] private Text nextHarvestedText;
    [SerializeField] private Text machinePriceText;
    [SerializeField] private Text messageText;
    
    private void Start()
    {
        Action callback;
        var upgradeType = LocalCacheManager.Load<CornFieldUpgradeType>(CornFieldReinforcement.CornFieldReinforcementDataTypeTag);
        switch (upgradeType)
        {
            case CornFieldUpgradeType.FieldTop:
            case CornFieldUpgradeType.FieldCenter:
            case CornFieldUpgradeType.FieldBottom:
                var (data, price, fieldCallback) = LocalCacheManager.Load<(PlantLineData, int, Action)>(CornFieldReinforcement.CornFieldReinforcementDataTag);
                callback = fieldCallback;
                SetFieldData(data, price);
                break;
            case CornFieldUpgradeType.Machine:
                var (machineLevel, machinePrice, machineCallback) = LocalCacheManager.Load<(int, int, Action)>(CornFieldReinforcement.CornFieldReinforcementDataTag);
                SetMachineData(machineLevel, machinePrice);
                callback = machineCallback;
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
        closeButton.OnClickAsObservable().Take(1).Subscribe(_ =>
        {
            transform.SetLocalScale(0);
            backgroundAnimator.SetTrigger(CloseTrigger);
            this.CallWaitForSeconds(.25f, () =>
            {
                TransitionManager.Instance.UnloadScene(GameScenes.ReinforcementDetail);
            });
        }).AddTo(this);
        purchaseButton.OnClickAsObservable()
            .Merge(releaseButton.OnClickAsObservable())
            .Take(1)
            .Subscribe(_ => { }, () =>
            {
                purchaseButton.interactable = false;
                releaseButton.interactable = false;
                // 購入処理
                callback?.Invoke();
                transform.SetLocalScale(0);
                backgroundAnimator.SetTrigger(CloseTrigger);
                this.CallWaitForSeconds(.25f, () =>
                {
                    TransitionManager.Instance.UnloadScene(GameScenes.ReinforcementDetail);
                    TransitionManager.Instance.UnloadScene(GameScenes.Reinforcement);
                });
            }).AddTo(this);
    }

    private void SetFieldData(PlantLineData data, int price)
    {
        if (data is null)
        {
            reinforceObject.SetActive(false);
            releaseObject.SetActive(true);
            machineObject.SetActive(false);
            purchaseButton.gameObject.SetActive(false);
            releaseButton.gameObject.SetActive(true);
            releasePriceText.text = price.ToString();
            messageText.text = ScriptLocalization.UI.CornFiledUpgradePopup;
        }
        else
        {
            reinforceObject.SetActive(true);
            releaseObject.SetActive(false);
            purchaseButton.gameObject.SetActive(true);
            releaseButton.gameObject.SetActive(false);
            machineObject.SetActive(false);
            reinforcePriceText.text = price.ToString();
            var nextRank = CornFieldReinforcement.GetNextRank(data.Level);
            var upgradeType = FieldUpgradeData.PlantTypeToUpgradeType(data.Type);
            var fieldData = SpreadsheetDataManager.Instance.GetBaseDataList<FieldUpgradeData>(Const.FieldUpgradeDataSheet);
            var currentHarvestCount = fieldData.FirstOrDefault(x => x.Type == upgradeType && x.level == (int)data.Level)?.harvested ?? 1;
            var nextHarvestCount = fieldData.FirstOrDefault(x => x.Type == upgradeType && x.level == (int)nextRank)?.harvested ?? 1;
            currentSeedling.SetSeedling(data.Level);
            currentSignBoard.text = string.Format(SigbBoardFormat, currentHarvestCount);
            nextSeedling.SetSeedling(nextRank);
            nextSignBoard.text = string.Format(SigbBoardFormat, nextHarvestCount);
            messageText.text = ScriptLocalization.UI.CornFieldReleasePopup;
        }
    }
    private void SetMachineData(int machineLevel, int price)
    {
        reinforceObject.SetActive(false);
        releaseObject.SetActive(false);
        machineObject.SetActive(true);
        purchaseButton.gameObject.SetActive(true);
        releaseButton.gameObject.SetActive(false);
        var fieldData = SpreadsheetDataManager.Instance.GetBaseDataList<FieldUpgradeData>(Const.FieldUpgradeDataSheet);
        var machineList = fieldData.Where(data => data.Type == CornFieldUpgradeType.Machine).ToList();
        var currentMachineData = machineList.FirstOrDefault(data => data.level == machineLevel);
        var nextMachineData = machineList.FirstOrDefault(data => data.level == machineLevel + 1);
        var currentHarvestedCorn = currentMachineData?.harvested ?? 20;
        var nextHarvestedCorn = nextMachineData?.harvested ?? 20;
        currentMachineImage.DestroyAllChildrens();
        nextMachineImage.DestroyAllChildrens();
        Instantiate(currentMachineData.GetIconPrefab(), currentMachineImage);
        Instantiate(nextMachineData.GetIconPrefab(), nextMachineImage);
        currentHarvestedText.text = string.Format(harvestedTextFormat, currentHarvestedCorn.ToString());
        nextHarvestedText.text = string.Format(harvestedTextFormat, nextHarvestedCorn.ToString());
        machinePriceText.text = price.ToString();
        messageText.text = ScriptLocalization.UI.CornFiledUpgradePopup;
    }
}
