using System;
using System.Collections.Generic;
using UniRx;
using UnityEngine;
using UnityEngine.UI;

public class ShopListView : MonoBehaviour
{
    [SerializeField] private ScrollRect scrollRect;
    [SerializeField] private ShopItemView itemViewPrefab;
    [SerializeField] private ShopHeaderView headerView;
    private readonly List<(ItemCategory category, RectTransform content)> tabs = new List<(ItemCategory, RectTransform)>();
    public ScrollRect ScrollRect => scrollRect;

    private void Awake()
    {
        while (scrollRect.content.childCount > 0)
        {
            DestroyImmediate(scrollRect.content.GetChild(0).gameObject);
        }
        tabs.Add((ItemCategory.Recipe, scrollRect.content));
    }

    private void Start()
    {
        headerView.Tab.Subscribe(tab =>
        {
            tabs.ForEach(x =>
            {
                x.content.gameObject.SetActive(x.category == tab);
                if (x.category == tab)
                {
                    scrollRect.content = x.content;
                    LayoutRebuilder.ForceRebuildLayoutImmediate(scrollRect.content);
                    scrollRect.verticalNormalizedPosition = 1;
                }
            });
        }).AddTo(this);
    }

    public void SetTab(ItemCategory category)
    {
        headerView.SetTab(category);
    }

    public ShopItemView AddItemView(ShopData shopData)
    {
        var tabCategory = GetTabCategory(shopData.Category);
        var index = tabs.FindIndex(x => x.category == tabCategory);
        if (index == -1)
        {
            index = tabs.Count;
            tabs.Add((tabCategory, Instantiate(scrollRect.content, scrollRect.content.parent)));
        }
        return Instantiate(itemViewPrefab, tabs[index].content);
    }

    private ItemCategory GetTabCategory(ItemCategory category)
    {
        switch (category)
        {
            case ItemCategory.Material:
                return ItemCategory.Material;
            case ItemCategory.Recipe:
            case ItemCategory.Pan:
                return ItemCategory.Recipe;
            default:
                throw new ArgumentOutOfRangeException(nameof(category), category, null);
        }
    }

    public void ForceRebuildContent()
    {
        LayoutRebuilder.ForceRebuildLayoutImmediate(scrollRect.content);
        scrollRect.verticalNormalizedPosition = 1;
    }
}
