using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using TMPro;

public class InventorySceneSetup
{
    [MenuItem("Tools/Create Player")]
    public static void CreatePlayer()
    {
        var go = new GameObject("Player");

        var cc = go.AddComponent<CharacterController>();
        cc.height = 1.8f;
        cc.radius = 0.5f;
        cc.center = new Vector3(0, 0.9f, 0);

        var character = go.AddComponent<charecter>();
        character.walkSpeed = 5f;
        character.runSpeed = 9f;
        character.crouchSpeed = 2.5f;
        character.jumpHeight = 1.5f;
        character.gravity = -9.81f;

        GameObject body = GameObject.CreatePrimitive(PrimitiveType.Capsule);
        body.name = "Body";
        body.transform.SetParent(go.transform);
        body.transform.localPosition = Vector3.zero;
        GameObject.Destroy(body.GetComponent<Collider>());

        GameObject head = new GameObject("Head");
        head.transform.SetParent(go.transform);
        head.transform.localPosition = new Vector3(0, 0.8f, 0);
        character.head = head.transform;

        GameObject camObj = new GameObject("PlayerCamera");
        camObj.transform.SetParent(head.transform);
        camObj.transform.localPosition = new Vector3(0, 0.1f, 0);
        var cam = camObj.AddComponent<Camera>();
        cam.tag = "MainCamera";

        var existingCam = GameObject.FindGameObjectWithTag("MainCamera");
        if (existingCam != null && existingCam != camObj)
        {
            GameObject.Destroy(existingCam);
        }

        go.tag = "Player";
        go.transform.position = new Vector3(0, 2, -5);

        Selection.activeGameObject = go;
        Debug.Log("[Tools] Создан игрок!");
    }

    [MenuItem("Tools/Create Item Prefab")]
    public static void CreateItemPrefab()
    {
        var itemGO = new GameObject("NewItem");
        itemGO.AddComponent<WorldItem>();

        var sphere = itemGO.AddComponent<SphereCollider>();
        sphere.radius = 0.5f;
        sphere.isTrigger = true;

        var visual = GameObject.CreatePrimitive(PrimitiveType.Cube);
        visual.name = "Visual";
        visual.transform.SetParent(itemGO.transform);
        visual.transform.localPosition = Vector3.zero;
        visual.transform.localScale = new Vector3(0.3f, 0.3f, 0.3f);
        GameObject.Destroy(visual.GetComponent<Collider>());

        Selection.activeGameObject = itemGO;
        Debug.Log("[Tools] Создан префаб предмета!");
    }

    [MenuItem("Tools/Create Test Item in Scene")]
    public static void CreateTestItem()
    {
        // Создаём тестовый предмет в сцене
        var itemGO = new GameObject("TestItem");
        itemGO.transform.position = new Vector3(0, 0.5f, 3);

        // Визуал
        var visual = GameObject.CreatePrimitive(PrimitiveType.Cube);
        visual.name = "Visual";
        visual.transform.SetParent(itemGO.transform);
        visual.transform.localPosition = Vector3.zero;
        visual.transform.localScale = Vector3.one * 0.3f;
        GameObject.Destroy(visual.GetComponent<Collider>());

        // Компонент предмета
        var worldItem = itemGO.AddComponent<WorldItem>();
        worldItem.pickupDelay = 0f; // мгновенный подбор
        worldItem.useFactory = false;

        // Тестовые данные
        var testItem = ScriptableObject.CreateInstance<ItemData>();
        testItem.id = "test_item";
        testItem.itemName = "Тестовый предмет";
        testItem.description = "Просто тестовый предмет";
        testItem.type = ItemType.Material;
        testItem.maxStack = 64;

        worldItem.itemData = testItem;
        worldItem.amount = 5;

        // Коллайдер для подбора (trigger для обычных коллайдеров)
        var box = itemGO.AddComponent<BoxCollider>();
        box.isTrigger = true;
        box.size = Vector3.one;

        Selection.activeGameObject = itemGO;
        Debug.Log("[Tools] Создан тестовый предмет! Подойдите к нему игроком.");
    }

    [MenuItem("Tools/Setup Inventory Scene")]
    public static void SetupScene()
    {
        var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
        var rootObjects = scene.GetRootGameObjects();

        foreach (var root in rootObjects)
        {
            if (root.GetComponent<InventoryManager>() != null)
            {
                Debug.LogWarning("InventoryManager уже существует!");
                return;
            }
        }

        // Создаём GameManager
        var gameManager = new GameObject("GameManager");
        var im = gameManager.AddComponent<InventoryManager>();
        gameManager.AddComponent<InventoryExampleItems>();
        gameManager.AddComponent<InventoryTester>();

        // Создаём Canvas
        var canvasGO = new GameObject("InventoryCanvas");
        var canvas = canvasGO.AddComponent<Canvas>();
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;
        canvas.sortingOrder = 100;
        canvasGO.AddComponent<GraphicRaycaster>();

        // Создаём панель инвентаря
        var inventoryPanel = CreatePanel(canvasGO.transform, "InventoryPanel", new Color(0.15f, 0.15f, 0.15f, 0.95f));
        var inventoryRect = inventoryPanel.GetComponent<RectTransform>();
        SetRect(inventoryRect, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(500, 300));

        // Заголовок
        CreateTitle(inventoryPanel.transform, "Инвентарь", new Vector2(0, 130));

        // Сетка инвентаря (4x9 = 36 слотов)
        var inventoryGrid = CreateGrid(inventoryPanel.transform, "InventoryGrid", 9, 4, 50, 4, new Vector2(10, 40));
        im.slots = CreateSlots(inventoryGrid, "InventorySlot_", 0, 36);

        // Создаём хотбар
        var hotbarPanel = CreatePanel(canvasGO.transform, "HotbarPanel", new Color(0.1f, 0.1f, 0.1f, 0.9f));
        var hotbarRect = hotbarPanel.GetComponent<RectTransform>();
        SetRect(hotbarRect, new Vector2(0.5f, 0f), new Vector2(0.5f, 0f), new Vector2(0, 15), new Vector2(460, 60));

        var hotbarGrid = CreateGrid(hotbarPanel.transform, "HotbarGrid", 9, 1, 50, 4, new Vector2(10, 10));
        im.hotbarSlots = CreateSlots(hotbarGrid, "HotbarSlot_", 0, 9);

        // Подключаем ссылку на панель
        im.inventoryPanel = inventoryPanel;
        im.inventoryCanvas = canvas;

        // Скрываем панель
        inventoryPanel.SetActive(false);

        Debug.Log("[Tools] Инвентарь настроен! (36 слотов + 9 хотбар)");
    }

    static GameObject CreatePanel(Transform parent, string name, Color color)
    {
        var panel = new GameObject(name);
        panel.transform.SetParent(parent, false);
        panel.AddComponent<RectTransform>();
        panel.AddComponent<Image>().color = color;
        return panel;
    }

    static void SetRect(RectTransform rect, Vector2 anchorMin, Vector2 anchorMax, Vector2 anchoredPosition, Vector2 sizeDelta)
    {
        rect.anchorMin = anchorMin;
        rect.anchorMax = anchorMax;
        rect.pivot = new Vector2(0.5f, 0.5f);
        rect.anchoredPosition = anchoredPosition;
        rect.sizeDelta = sizeDelta;
    }

    static void CreateTitle(Transform parent, string text, Vector2 position)
    {
        var titleObj = new GameObject("Title");
        titleObj.transform.SetParent(parent, false);
        var rect = titleObj.AddComponent<RectTransform>();
        rect.anchorMin = new Vector2(0, 1);
        rect.anchorMax = new Vector2(1, 1);
        rect.pivot = new Vector2(0.5f, 1);
        rect.anchoredPosition = position;
        rect.sizeDelta = new Vector2(-20, 30);

        var tmp = titleObj.AddComponent<TextMeshProUGUI>();
        tmp.text = text;
        tmp.fontSize = 18;
        tmp.alignment = TextAlignmentOptions.Center;
        tmp.color = Color.white;
    }

    static Transform CreateGrid(Transform parent, string name, int cols, int rows, float cellSize, float spacing, Vector2 offset)
    {
        var gridObj = new GameObject(name);
        gridObj.transform.SetParent(parent, false);
        var rect = gridObj.AddComponent<RectTransform>();
        rect.anchorMin = Vector2.zero;
        rect.anchorMax = Vector2.one;
        rect.offsetMin = offset;
        rect.offsetMax = -offset;

        var grid = gridObj.AddComponent<GridLayoutGroup>();
        grid.cellSize = new Vector2(cellSize, cellSize);
        grid.spacing = new Vector2(spacing, spacing);
        grid.startCorner = GridLayoutGroup.Corner.UpperLeft;
        grid.startAxis = GridLayoutGroup.Axis.Horizontal;
        grid.constraint = GridLayoutGroup.Constraint.FixedColumnCount;
        grid.constraintCount = cols;

        return gridObj.transform;
    }

    static Slot[] CreateSlots(Transform parent, string prefix, int startIndex, int count)
    {
        var slots = new Slot[count];
        var slotSize = 50f;
        var emptyColor = new Color(0.25f, 0.25f, 0.25f, 0.8f);

        for (int i = 0; i < count; i++)
        {
            var slotObj = new GameObject(prefix + (startIndex + i));
            slotObj.transform.SetParent(parent, false);
            slotObj.AddComponent<RectTransform>().sizeDelta = new Vector2(slotSize, slotSize);

            var bg = slotObj.AddComponent<Image>();
            bg.color = emptyColor;

            var slot = slotObj.AddComponent<Slot>();
            slot.slotIndex = startIndex + i;

            // Icon
            var iconObj = new GameObject("Icon");
            iconObj.transform.SetParent(slotObj.transform, false);
            var iconRect = iconObj.AddComponent<RectTransform>();
            iconRect.anchorMin = Vector2.zero;
            iconRect.anchorMax = Vector2.one;
            iconRect.offsetMin = new Vector2(4, 4);
            iconRect.offsetMax = new Vector2(-4, -4);
            slot.iconImage = iconObj.AddComponent<Image>();
            slot.iconImage.preserveAspect = true;
            slot.iconImage.enabled = false;

            // Amount panel
            var amountObj = new GameObject("AmountPanel");
            amountObj.transform.SetParent(slotObj.transform, false);
            var amountRect = amountObj.AddComponent<RectTransform>();
            amountRect.anchorMin = Vector2.one;
            amountRect.anchorMax = Vector2.one;
            amountRect.pivot = new Vector2(1, 0);
            amountRect.anchoredPosition = new Vector2(-2, 2);
            amountRect.sizeDelta = new Vector2(22, 22);
            slot.amountPanel = amountObj;
            slot.amountPanel.SetActive(false);

            amountObj.AddComponent<Image>().color = new Color(0, 0, 0, 0.7f);

            var amountTextObj = new GameObject("Text");
            amountTextObj.transform.SetParent(amountObj.transform, false);
            amountTextObj.AddComponent<RectTransform>().sizeDelta = new Vector2(20, 20);
            slot.amountText = amountTextObj.AddComponent<TextMeshProUGUI>();
            slot.amountText.fontSize = 14;
            slot.amountText.alignment = TextAlignmentOptions.Right;
            slot.amountText.color = Color.white;
            slot.amountText.fontStyle = FontStyles.Bold;

            // Drag & Drop
            var dragDrop = slotObj.AddComponent<InventoryDragDrop>();
            dragDrop.slot = slot;
            dragDrop.slotIndex = slot.slotIndex;

            slots[i] = slot;
        }

        return slots;
    }
}