using System;
using System.Collections.Generic;
using System.Linq;
using MyGame.Scripts;
using UniRx;
using UnityEngine;

namespace MyGame.Scenes.marketing.Scripts
{
    public class ShopCustomize : MonoBehaviour
    {
        [SerializeField] private MarketView marketView;
        [SerializeField] private ShopCustomizeView customizeView;
        [SerializeField] private ShopCustomizeSelector customizeSelector;
        private void Start()
        {
            SoundManager.Instance.PlayBGM("bgm_marketing");
            var gameData = GameDataManager.GameData;
            var customizeDataList = SpreadsheetDataManager.Instance.GetBaseDataList<ShopCustomizeData>(Const.ShopCustomizeDataSheet);
#if UNITY_EDITOR
            Debug.Log($@"
coin {gameData.ShopCustomizeCoin}
myItems {string.Join(",", gameData.ShopCustomizeMyItems.Select(x => x.ToString()))}
");
#endif
            
            if (!gameData.FinishedFlags.HasFlag(TutorialFlag.ShopCustomize))
            {
                gameData.FinishedFlags |= TutorialFlag.ShopCustomize;
                GameDataManager.SaveGameData();
                ShopCustomizeTutorialDialog.ShowDialog();
            }
            customizeView.SetLevel(gameData.ShopCustomizeLevel);
            ShopCustomizeCoinManager.Instance.ChangeCoin(gameData.ShopCustomizeCoin);
            
            customizeView.OnCloseObservable.Subscribe(_ =>
            {
                GameDataManager.SaveGameData(); // 設定を保存
                TransitionManager.Instance.LoadScene(GameScenes.marketing);
            }).AddTo(this);
            customizeView.OnClickInfoObservable.Subscribe(_ =>
            {
                ShopCustomizeInfoDialog.ShowDialog();
            }).AddTo(this);
            
            customizeSelector.Initialize(ShopCustomizeCategory.Category1);
            customizeSelector.SelecedCategory.Pairwise().Subscribe(x =>
            {
                marketView.SetHighlight(x.Previous, false);
                marketView.SetHighlight(x.Current, true);
            }).AddTo(this);
            
            // カード生成
            var categories = (ShopCustomizeCategory[])Enum.GetValues(typeof(ShopCustomizeCategory));
            foreach (var category in categories)
            {
                var list = customizeDataList.Where(data => data.Category == category).ToList();
                var selectedId = gameData.ShopCustomizeSettings.GetSetting(category);
                ShopCustomizeItem selectedItem = null;
                foreach (var customizeData in list)
                {
                    var selectSubject = new Subject<Unit>().AddTo(this);
                    var item = customizeSelector.GenerateItem(category);
                    item.SetData(customizeData);
                    
                    if (gameData.ShopCustomizeMyItems.Contains(customizeData.id))
                    {
                        item.SetState(ShopCustomizeItemState.Purchased);
                    }
                    else if (gameData.ViewedShopLevel >= customizeData.level)
                    {
                        item.SetState(ShopCustomizeItemState.Unlock);
                    }
                    else
                    {
                        item.SetState(ShopCustomizeItemState.Lock);
                    }
                    
                    item.SelectObservable.Merge(selectSubject).Subscribe(_ =>
                    {
                        if (item != selectedItem)
                        {
                            selectedItem.SetState(ShopCustomizeItemState.Purchased);
                            selectedItem = item;
                        }
                        item.SetState(ShopCustomizeItemState.Selected);
                        gameData.ShopCustomizeSettings.SetSetting(customizeData);
                        marketView.SetItem(customizeData);
                        if (customizeSelector.SelecedCategory.Value == category)
                        {
                            marketView.SetHighlight(category, true);
                        }
                    }).AddTo(this);
                    item.DetailObservable.Subscribe(_ =>
                    {
                        ShopCustomizePurchaseDialog.ShowDialog(customizeData, true);
                    }).AddTo(this);
                    item.PurchaseObservable.Subscribe(_ =>
                    {
                        // purchase dialog
                        ShopCustomizePurchaseDialog.ShowDialog(customizeData, false, () =>
                        {
                            PurchaseItem(customizeData);
                            Market.Instance.UpdateBonus(GetBonusList(gameData.ShopCustomizeLevel));
                            selectSubject.OnNext(Unit.Default);
                        });
                    }).AddTo(this);
                    
                    // 現在設定しているのアイテムを選択
                    if (customizeData.id == selectedId)
                    {
                        selectedItem = item;
                        selectSubject.OnNext(Unit.Default);
                    }
                }
            }
        }

        private void PurchaseItem(ShopCustomizeData customizeData)
        {
            var gameData = GameDataManager.GameData;
            ShopCustomizeCoinManager.Instance.SubCoin(customizeData.price);
            gameData.ShopCustomizeCoin = ShopCustomizeCoinManager.Instance.OwnCoin;
            gameData.ShopCustomizePoint += customizeData.point;
            gameData.ShopCustomizeMyItems = gameData.ShopCustomizeMyItems.Append(customizeData.id).ToArray();
           
            var customizeLevelList = SpreadsheetDataManager.Instance.GetBaseDataList<ShopCustomizeLevelData>(Const.ShopCustomizeLevelDataSheet);
            var level = customizeLevelList.LastOrDefault(data => data.point <= gameData.ShopCustomizePoint)?.level ?? 1;
            gameData.ShopCustomizeLevel = level;
            GameDataManager.SaveGameData();
            customizeView.SetLevel(gameData.ShopCustomizeLevel);
        }
        
        /*
         * 現在のボーナスレベルと値
         */
        public static Dictionary<ShopCustomizeBonusCategory, (int bonusLevel, int value)> GetBonusList(int level)
        {
            var customizeBonusList = SpreadsheetDataManager.Instance.GetBaseDataList<ShopCustomizeBonusData>(Const.ShopCustomizeBonusDataSheet);
            var categories = (ShopCustomizeBonusCategory[])Enum.GetValues(typeof(ShopCustomizeBonusCategory));
            var list = new Dictionary<ShopCustomizeBonusCategory, (int bonusLevel, int value)>();
            foreach (var category in categories)
            {
                if (customizeBonusList.Where(data => data.level <= level).LastOrDefault(data => data.Category == category) is ShopCustomizeBonusData bonusData)
                {
                    list.Add(category, (bonusData.bonusLevel, bonusData.value));
                    continue;
                }
                list.Add(category, (0, 0));
            }
            return list;
        }
    }
}