using System;
using System.Collections;
using System.Collections.Generic;
using Cogwheel;
using UnityEngine;
using UnityEngine.UIElements;

public class CogwheelConsole : MonoBehaviour
{
    [SerializeField] private UIDocument uiDocument;
    
    private VisualElement _consoleRoot;
    private TextField _inputField;
    private Label _outputLabel;
    private ScrollView _scrollView;
    
    private void Start()
    {
        _consoleRoot = uiDocument.rootVisualElement;
        _inputField = _consoleRoot.Q<TextField>("InputTextField");
        _outputLabel = _consoleRoot.Q<Label>("ConsoleOutputLabel");
        _scrollView = _consoleRoot.Q<ScrollView>("ConsoleScrollView");
        
        
        
        Hide(); 
    }

    private void Update()
    {
        HandleInput();
    }

    private void HandleInput()
    {
        if (_inputField.panel.focusController.focusedElement == _inputField && Input.GetKeyDown(KeyCode.Return))
        {
            SubmitInput();
        }
        
        if (COGWHEEL.Settings.EnableConsole && Input.GetKeyDown(COGWHEEL.Settings.ConsoleToggleKey) && _inputField.panel.focusController.focusedElement != _inputField)
        {
            if (_consoleRoot.ClassListContains("active"))
            {
                Hide();
            }
            else
            {
                Show();
            }
        }
    }

    private void Show()
    {
        _consoleRoot.AddToClassList("active");
        _consoleRoot.RemoveFromClassList("hidden");
        ScrollToBottom();
    }
    
    private void Hide()
    {
        _consoleRoot.RemoveFromClassList("active");
        _consoleRoot.AddToClassList("hidden");
    }

    private void SubmitInput()
    {
        Log("> " + "<color=#555555><i>" + _inputField.value + "</i></color>");
        var success = COGWHEEL.CommandsManager.RunCommand(_inputField.value);
        _inputField.value = "";
        _inputField.Focus();
        ScrollToBottom();
    }
    
    private void ScrollToBottom()
    {
        _scrollView.schedule.Execute(() =>
        {
            _scrollView.verticalScroller.value = _scrollView.contentContainer.resolvedStyle.height;
        }).ExecuteLater(10);
    }
    
    public void Log(string message)
    {
        _outputLabel.text += message + "\n";
    }
    
    public void LogError(string message)
    {
        Log($"<color=red>ERROR: {message}</color>");
    }

    public void LogWarning(string message)
    {
        Log($"<color=yellow>WARNING: {message}</color>");
    }

    public void Clear()
    {
        _outputLabel.text = "";
    }
}
