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

public class CraftingManager : MonoBehaviour
{
    public static CraftingManager Instance;

    [Header("UI References")]
    public GameObject craftingPanel;
    public Slot[] inputSlots;   // 9 слотов для входа (как в крафтинге)
    public Slot outputSlot;     // 1 слот для результата
    public Text recipeNameText;
    public Button craftButton;

    [Header("Recipe Database")]
    public List<CraftingRecipe> recipes;

    private Dictionary<string, CraftingRecipe> _recipeDict;

    void Awake()
    {
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);

        _recipeDict = new Dictionary<string, CraftingRecipe>();
        foreach (var recipe in recipes)
        {
            string key = GetRecipeKey(recipe);
            _recipeDict[key] = recipe;
        }
    }

    void Start()
    {
        if (craftingPanel != null)
            craftingPanel.SetActive(false);

        if (craftButton != null)
            craftButton.onClick.AddListener(Craft);
    }

    public void ToggleCrafting()
    {
        if (craftingPanel != null)
        {
            craftingPanel.SetActive(!craftingPanel.activeSelf);
            if (craftingPanel.activeSelf)
                CheckRecipe();
        }
    }

    // Собираем ключ из текущих ингредиентов в слотах
    string GetCurrentIngredientsKey()
    {
        var ingredients = new List<string>();
        foreach (var slot in inputSlots)
        {
            if (!slot.IsEmpty)
            {
                ingredients.Add(slot.item.id);
            }
        }
        ingredients.Sort();
        return string.Join(",", ingredients);
    }

    // Проверяем рецепт
    public void CheckRecipe()
    {
        string key = GetCurrentIngredientsKey();

        if (_recipeDict.TryGetValue(key, out CraftingRecipe recipe))
        {
            // Проверяем хватает ли количества
            bool canCraft = true;
            int slotIndex = 0;

            foreach (var ingredientId in recipe.ingredients)
            {
                int required = recipe.amounts[System.Array.IndexOf(recipe.ingredients, ingredientId)];
                int have = 0;

                for (int i = 0; i < inputSlots.Length; i++)
                {
                    if (!inputSlots[i].IsEmpty && inputSlots[i].item.id == ingredientId)
                    {
                        have += inputSlots[i].amount;
                    }
                }

                if (have < required)
                {
                    canCraft = false;
                    break;
                }
            }

            if (canCraft)
            {
                // Показываем результат
                if (InventoryManager.Instance.itemDatabase.Find(x => x.id == recipe.resultId) is ItemData resultItem)
                {
                    outputSlot.SetItem(resultItem, recipe.resultAmount);
                    if (recipeNameText != null)
                        recipeNameText.text = resultItem.itemName;

                    if (craftButton != null)
                        craftButton.interactable = true;
                }
            }
            else
            {
                outputSlot.Clear();
                if (recipeNameText != null)
                    recipeNameText.text = "Unknown recipe";
                if (craftButton != null)
                    craftButton.interactable = false;
            }
        }
        else
        {
            outputSlot.Clear();
            if (recipeNameText != null)
                recipeNameText.text = "";
            if (craftButton != null)
                craftButton.interactable = false;
        }
    }

    // Выполнить крафтинг
    public void Craft()
    {
        string key = GetCurrentIngredientsKey();

        if (_recipeDict.TryGetValue(key, out CraftingRecipe recipe))
        {
            // Удаляем ингредиенты
            foreach (var ingredientId in recipe.ingredients)
            {
                int required = recipe.amounts[System.Array.IndexOf(recipe.ingredients, ingredientId)];
                InventoryManager.Instance.RemoveItem(ingredientId, required);
            }

            // Добавляем результат
            int remaining = InventoryManager.Instance.AddItem(recipe.resultId, recipe.resultAmount);
            if (remaining > 0)
            {
                Debug.LogWarning($"Inventory full! Couldn't add {remaining} items.");
            }

            // Очищаем слоты ввода
            foreach (var slot in inputSlots)
            {
                slot.Clear();
            }

            // Пересматриваем рецепт
            CheckRecipe();

            // Обновляем инвентарь
            foreach (var slot in InventoryManager.Instance.slots)
            {
                slot.UpdateSlotUI();
            }
        }
    }

    // Добавить рецепт
    public void AddRecipe(string resultId, int resultAmount, string[] ingredients, int[] amounts)
    {
        var recipe = new CraftingRecipe
        {
            resultId = resultId,
            resultAmount = resultAmount,
            ingredients = ingredients,
            amounts = amounts
        };

        recipes.Add(recipe);
        string key = GetRecipeKey(recipe);
        _recipeDict[key] = recipe;
    }

    string GetRecipeKey(CraftingRecipe recipe)
    {
        var sorted = new List<string>(recipe.ingredients);
        sorted.Sort();
        return string.Join(",", sorted);
    }

    [System.Serializable]
    public class CraftingRecipe
    {
        public string resultId;
        public int resultAmount = 1;
        public string[] ingredients;
        public int[] amounts;
    }
}