using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.UI;

public class BaseModelSelector : MonoBehaviour
{
    private Canvas canvas;
    private GameObject buttonPrefab;
    private Button[] modelButtons;
    private BaseModel selectedModel = null; // Gemerkte Auswahl!
    
    public ModelManager modelManager; // <-- ziehen wir im Inspector rein
    
    void Start()
    {
        SetupEventSystem();
        SetupCanvas();
        CreatePrefabButtons();
    }

    void SetupEventSystem()
    {
        if (FindObjectOfType<EventSystem>() == null)
        {
            GameObject eventSystemGO = new GameObject("EventSystem");
            var eventSys = eventSystemGO.AddComponent<EventSystem>();
            //var inputModule = eventSystemGO.AddComponent<UnityEngine.InputSystem.UI.InputSystemUIInputModule>();
            var MetaInputModule = eventSystemGO.AddComponent<OVRInputModule>();
            
        }
        else
        {
            Debug.Log("EventSystem existiert bereits — neues wird nicht erstellt.");
        }
        
    }

    void SetupCanvas()
    {
        GameObject canvasGO = new GameObject("ModelSelectorCanvas");
        canvas = canvasGO.AddComponent<Canvas>();
        canvas.renderMode = RenderMode.WorldSpace;

        var cameraRig = GameObject.Find("[BuildingBlock] Camera Rig");
        if (cameraRig != null)
        {
            var centerEye = cameraRig.transform.Find("TrackingSpace/CenterEyeAnchor");
            canvas.worldCamera = centerEye.GetComponent<Camera>();
            canvas.transform.position = centerEye.position + centerEye.forward * 2f;
            canvas.transform.rotation = Quaternion.LookRotation(canvas.transform.position - centerEye.position);
        }
        else
        {
            Debug.LogError("Camera Rig nicht gefunden!");
        }

        canvasGO.AddComponent<CanvasScaler>().uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        canvasGO.AddComponent<GraphicRaycaster>();
        canvasGO.AddComponent<OVRRaycaster>();
    }
    

    void CreatePrefabButtons()
    {
        float startY = 0; // Anfangsposition auf Y-Achse
        float buttonHeight = 0.5f; // Abstand zwischen den Buttons
        foreach (var baseModel in ModelList.BaseModels)
        {
            GameObject buttonGO = SetupPrefab(baseModel);
            buttonGO.transform.SetParent(canvas.transform);
            RectTransform rt = buttonGO.GetComponent<RectTransform>();
            var collider = buttonGO.AddComponent<BoxCollider>();
            rt.sizeDelta = new Vector2(300, 50);
            rt.localScale = Vector3.one * 0.005f;// Größe des Buttons
            rt.localPosition = new Vector3(0, startY, 0); // Position im Canvas
            rt.localRotation = Quaternion.identity;
            
            // Collider richtig setzen
            collider.size = new Vector3(rt.sizeDelta.x * rt.localScale.x, rt.sizeDelta.y * rt.localScale.y, 1f);
            collider.center = Vector3.zero;

            buttonGO.GetComponent<Button>().onClick.AddListener(() => OnModelButtonClicked(baseModel));
            startY -= buttonHeight; // Nächster Button weiter unten
        }

    }
    // Wenn ein Button geklickt wird
    public void OnModelButtonClicked(BaseModel model)
    {
        selectedModel = model;
        Debug.Log($"Ausgewähltes Modell: {selectedModel.nameHuman}");

        if (modelManager != null)
        {
            modelManager.LoadSelectedModel(selectedModel);
            ReturnButtonSpawner.SpawnReturnButton(modelManager.transform, this.canvas.gameObject);
        }
        else
        {
            Debug.LogError("ModelManager ist nicht zugewiesen!");
        }
        // --> Canvas unsichtbar machen!
        if (canvas != null)
        {
            canvas.gameObject.SetActive(false);
        }
    }

    // Öffentliche Funktion: Aktuell gewähltes Modell zurückgeben
    public BaseModel GetSelectedModel()
    {
        return selectedModel;
    }
    
    public static GameObject SetupPrefab(BaseModel model)
    {
        // Hauptobjekt
        GameObject buttonGO = new GameObject("ModelButton_" + model.nameId);
        buttonGO.AddComponent<RectTransform>();

        var button = buttonGO.AddComponent<Button>();

        var image = buttonGO.AddComponent<Image>();

        // Lade individuellen Hintergrund aus Resources/UI/ButtonBackgrounds/
        var backgroundSprite = Resources.Load<Sprite>($"sprites/default");
        if (backgroundSprite != null)
            image.sprite = backgroundSprite;
        else
            image.color = new Color(0.2f, 0.2f, 0.2f, 0.8f); // Fallback-Farbe

        // Größe
        RectTransform rt = buttonGO.GetComponent<RectTransform>();
        rt.sizeDelta = new Vector2(300, 100);

        // === Icon ===
        GameObject iconGO = new GameObject("Icon");
        iconGO.transform.SetParent(buttonGO.transform, false);
        var iconImage = iconGO.AddComponent<Image>();
        iconImage.sprite = Resources.Load<Sprite>($"sprites/"+model.nameId);

        RectTransform iconRT = iconGO.GetComponent<RectTransform>();
        iconRT.anchorMin = new Vector2(0, 0.5f);
        iconRT.anchorMax = new Vector2(0, 0.5f);
        iconRT.pivot = new Vector2(0, 0.5f);
        iconRT.anchoredPosition = new Vector2(10, 0);
        iconRT.sizeDelta = new Vector2(44, 22);

        // === Titel ===
        GameObject titleGO = new GameObject("TitleText");
        titleGO.transform.SetParent(buttonGO.transform, false);
        var titleText = titleGO.AddComponent<TextMeshProUGUI>();
        titleText.text = model.nameHuman;
        titleText.fontSize = 24;

        RectTransform titleRT = titleGO.GetComponent<RectTransform>();
        titleRT.anchorMin = new Vector2(0, 1);
        titleRT.anchorMax = new Vector2(1, 1);
        titleRT.pivot = new Vector2(0, 1);
        titleRT.anchoredPosition = new Vector2(60, -10);
        titleRT.sizeDelta = new Vector2(-70, 30);

        return buttonGO;
    }

}

    

