using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using TMPro;

namespace MaskShop
{
    /// <summary>
    /// Displays ogre requests in UI with typewriter effect
    /// </summary>
    public class RequestDisplayUI : MonoBehaviour
    {
        [Header("UI References")]
        [SerializeField] private GameObject requestPanel;
        [SerializeField] private TextMeshProUGUI requestText;
        [SerializeField] private TextMeshProUGUI ogreNameText;
        //[SerializeField] private Image ogrePortrait;

        [Header("Typewriter Settings")]
        [SerializeField] private float charactersPerSecond = 30f;
        [SerializeField] private bool skipOnClick = true;
        [SerializeField] private KeyCode skipKey = KeyCode.Space;

        [Header("Animation Settings")]
        [SerializeField] private bool usePanelAnimation = true;
        [SerializeField] private float panelFadeInDuration = 0.3f;
        [SerializeField] private float panelSlideDistance = 50f;

        [Header("Sound Effects (Optional)")]
        [SerializeField] private AudioSource audioSource;
        [SerializeField] private AudioClip typeSound;
        [SerializeField] private AudioClip completeSound;
        [SerializeField] private float typeSoundPitch = 1f;
        [SerializeField] private bool playTypeSoundPerCharacter = false;
        [SerializeField] private int typeSoundEveryNCharacters = 3;

        [Header("Visual Feedback")]
        [SerializeField] private GameObject continueIndicator;
        [SerializeField] private bool showCursorWhileTyping = true;
        [SerializeField] private string cursorCharacter = "▋";

        [Header("Debug")]
        [SerializeField] private bool showDebugInfo = true;

        // State
        private Coroutine typewriterCoroutine;
        private bool isTyping = false;
        private bool skipRequested = false;
        private MaskRequest currentRequest;
        private CanvasGroup panelCanvasGroup;
        private RectTransform panelRectTransform;
        private Vector2 originalPanelPosition;

        private void Awake()
        {
            // Setup canvas group for animations
            if (requestPanel != null)
            {
                panelCanvasGroup = requestPanel.GetComponent<CanvasGroup>();
                if (panelCanvasGroup == null && usePanelAnimation)
                {
                    panelCanvasGroup = requestPanel.AddComponent<CanvasGroup>();
                }

                panelRectTransform = requestPanel.GetComponent<RectTransform>();
                if (panelRectTransform != null)
                {
                    originalPanelPosition = panelRectTransform.anchoredPosition;
                }
            }

            // Setup audio source
            if (audioSource == null)
            {
                audioSource = GetComponent<AudioSource>();
                if (audioSource == null && (typeSound != null || completeSound != null))
                {
                    audioSource = gameObject.AddComponent<AudioSource>();
                }
            }

            if (audioSource != null)
            {
                audioSource.playOnAwake = false;
            }

            // Hide continue indicator initially
            if (continueIndicator != null)
            {
                continueIndicator.SetActive(false);
            }

            // Hide panel initially
            HidePanel(true);
        }

        private void OnEnable()
        {
            OgreEvents.OnMaskRequested += OnMaskRequested;
            OgreEvents.OnRequestCompleted += OnRequestCompleted;
        }

        private void OnDisable()
        {
            OgreEvents.OnMaskRequested -= OnMaskRequested;
            OgreEvents.OnRequestCompleted -= OnRequestCompleted;
        }

        private void Update()
        {
            // Check for skip input
            /*if (skipOnClick && isTyping && Input.GetKeyDown(skipKey))
            {
                skipRequested = true;
            }*/
        }

        /// <summary>
        /// Called when a new mask request is made
        /// </summary>
        private void OnMaskRequested(MaskRequest request)
        {
            currentRequest = request;
            DisplayRequest(request);
        }

        /// <summary>
        /// Called when request is completed
        /// </summary>
        private void OnRequestCompleted(MaskRequest completedRequest)
        {
            if (completedRequest == currentRequest)
            {
                HidePanel();
            }
        }

        /// <summary>
        /// Displays the request with typewriter effect
        /// </summary>
        public void DisplayRequest(MaskRequest request)
        {
            if (request == null)
            {
                Debug.LogWarning("RequestDisplayUI: Received null request!");
                return;
            }

            // Stop any existing typewriter
            if (typewriterCoroutine != null)
            {
                StopCoroutine(typewriterCoroutine);
            }

            // Show panel with animation
            ShowPanel();

            // Update ogre info (if applicable)
            UpdateOgreInfo();

            // Start typewriter effect
            typewriterCoroutine = StartCoroutine(TypewriterEffect(request.requestText));

            if (showDebugInfo)
            {
                Debug.Log($"RequestDisplayUI: Displaying request - {request.requestText}");
            }
        }

        /// <summary>
        /// Typewriter coroutine
        /// </summary>
        private IEnumerator TypewriterEffect(string fullText)
        {
            isTyping = true;
            skipRequested = false;

            if (continueIndicator != null)
            {
                continueIndicator.SetActive(false);
            }

            if (requestText != null)
            {
                requestText.text = "";
            }

            float timePerCharacter = 1f / charactersPerSecond;
            int characterCount = 0;

            foreach (char character in fullText)
            {
                if (skipRequested)
                {
                    // Skip to end
                    if (requestText != null)
                    {
                        requestText.text = fullText;
                    }
                    break;
                }

                // Add character
                if (requestText != null)
                {
                    requestText.text += character;

                    // Show cursor while typing
                    if (showCursorWhileTyping)
                    {
                        requestText.text += $"<color=#00000000>{cursorCharacter}</color>";
                    }
                }

                characterCount++;

                // Play typing sound
                if (typeSound != null && audioSource != null)
                {
                    if (playTypeSoundPerCharacter || characterCount % typeSoundEveryNCharacters == 0)
                    {
                        audioSource.pitch = typeSoundPitch + Random.Range(-0.1f, 0.1f);
                        audioSource.PlayOneShot(typeSound, 0.3f);
                    }
                }

                // Wait before next character
                yield return new WaitForSeconds(timePerCharacter);

                // Remove cursor for next iteration
                if (showCursorWhileTyping && requestText != null)
                {
                    requestText.text = requestText.text.Replace($"<color=#00000000>{cursorCharacter}</color>", "");
                }
            }

            // Typing complete
            isTyping = false;

            // Ensure final text is clean
            if (requestText != null)
            {
                requestText.text = fullText;
            }

            // Play complete sound
            if (completeSound != null && audioSource != null)
            {
                audioSource.pitch = 1f;
                audioSource.PlayOneShot(completeSound);
            }

            // Show continue indicator
            if (continueIndicator != null)
            {
                continueIndicator.SetActive(true);
                AnimateContinueIndicator();
            }

            if (showDebugInfo)
            {
                Debug.Log("RequestDisplayUI: Typewriter effect complete");
            }
        }

        /// <summary>
        /// Shows the request panel with animation
        /// </summary>
        private void ShowPanel()
        {
            if (requestPanel == null)
            {
                Debug.LogWarning("RequestDisplayUI: Request panel not assigned!");
                return;
            }

            requestPanel.SetActive(true);

            if (usePanelAnimation && panelCanvasGroup != null)
            {
                // Fade in animation
                panelCanvasGroup.alpha = 0f;
                LeanTween.alphaCanvas(panelCanvasGroup, 1f, panelFadeInDuration)
                    .setEaseOutQuad();

                // Slide in animation
                if (panelRectTransform != null)
                {
                    Vector2 startPos = originalPanelPosition + new Vector2(0, panelSlideDistance);
                    panelRectTransform.anchoredPosition = startPos;

                    LeanTween.move(panelRectTransform, originalPanelPosition, panelFadeInDuration)
                        .setEaseOutBack();
                }
            }
        }

        /// <summary>
        /// Hides the request panel with animation
        /// </summary>
        private void HidePanel(bool immediate = false)
        {
            if (requestPanel == null)
                return;

            if (immediate || !usePanelAnimation || panelCanvasGroup == null)
            {
                requestPanel.SetActive(false);
                return;
            }

            // Fade out animation
            LeanTween.alphaCanvas(panelCanvasGroup, 0f, panelFadeInDuration * 0.7f)
                .setEaseInQuad()
                .setOnComplete(() => requestPanel.SetActive(false));

            // Slide out animation
            if (panelRectTransform != null)
            {
                Vector2 endPos = originalPanelPosition + new Vector2(0, -panelSlideDistance);
                LeanTween.move(panelRectTransform, endPos, panelFadeInDuration * 0.7f)
                    .setEaseInBack();
            }
        }

        /// <summary>
        /// Updates ogre information display
        /// </summary>
        private void UpdateOgreInfo()
        {
            // Generate random ogre name (you can customize this)
            if (ogreNameText != null)
            {
                string[] ogreNames = {
                    "Grok", "Throg", "Urzog", "Gorak", "Molog",
                    "Borgak", "Kragok", "Durgol", "Shagrok", "Zogmar"
                };
                string randomName = ogreNames[Random.Range(0, ogreNames.Length)];
                ogreNameText.text = randomName;
            }

            // TODO: Set ogre portrait if you have sprites
            // if (ogrePortrait != null)
            // {
            //     ogrePortrait.sprite = GetRandomOgreSprite();
            // }
        }

        /// <summary>
        /// Animates the continue indicator
        /// </summary>
        private void AnimateContinueIndicator()
        {
            if (continueIndicator == null)
                return;

            // Pulse animation
            LeanTween.scale(continueIndicator, Vector3.one * 1.1f, 0.5f)
                .setEaseInOutSine()
                .setLoopPingPong();
        }

        /// <summary>
        /// Manually shows a custom message
        /// </summary>
        public void ShowCustomMessage(string message)
        {
            if (typewriterCoroutine != null)
            {
                StopCoroutine(typewriterCoroutine);
            }

            ShowPanel();
            typewriterCoroutine = StartCoroutine(TypewriterEffect(message));
        }

        /// <summary>
        /// Manually hides the panel
        /// </summary>
        public void Hide()
        {
            HidePanel();
        }

        /// <summary>
        /// Skips the typewriter effect immediately
        /// </summary>
        public void SkipTypewriter()
        {
            skipRequested = true;
        }

        // Public getters
        public bool IsTyping() => isTyping;
        public MaskRequest GetCurrentRequest() => currentRequest;

        // Context menu for testing
        [ContextMenu("Test Typewriter")]
        private void TestTypewriter()
        {
            string testMessage = "Necesito una máscara que exprese furia, de colores atardecer, con una textura de tipo madera y que además tenga cuernos.";
            ShowCustomMessage(testMessage);
        }
    }
}