using ALArcade.ArabicTMP;
using DG.Tweening;
using UnityEngine;

namespace com.al_arcade.mcq
{
    using shared;
    using System.Collections;
    using static Unity.VisualScripting.Member;

    public class McqQuestionDisplay : MonoBehaviour
    {
        [Header("Settings")]
        [SerializeField] private float floatHeight = 6f;
        [SerializeField] private float followSpeed = 5f;
        [SerializeField] private float forwardOffset = 5f;

        [SerializeField] private ArabicTextMeshPro _questionText;
        [SerializeField] private ArabicTextMeshPro _sourceText;

        [Header("Answer Panels")]
        [SerializeField] private ArabicTextMeshPro[] AnswerTexts;
        [SerializeField] private MeshRenderer[] PanelRenderers;
        [SerializeField] private Color _baseColor;
        private GameObject _panel;
        private Transform _playerTransform;
        private bool _visible;

        public void Build(Transform playerTarget = null, bool Prefab = false)
        {
            var shader = Shader.Find("Universal Render Pipeline/Lit") ??
                         Shader.Find("Standard") ?? Shader.Find("Unlit/Color");
            if (!Prefab)
            {
                _panel = GameObject.CreatePrimitive(PrimitiveType.Cube);
                _panel.name = "QuestionPanel";
                _panel.transform.SetParent(transform);
                _panel.transform.localPosition = Vector3.zero;
                _panel.transform.localScale = new Vector3(12f, 2.5f, 0.1f);
                Destroy(_panel.GetComponent<Collider>());
                var panelMat = new Material(shader)
                { color = new Color(0.12f, 0.12f, 0.5f, 0.95f) };
                _panel.GetComponent<Renderer>().material = panelMat;


                var bar = GameObject.CreatePrimitive(PrimitiveType.Cube);
                bar.name = "AccentBar";
                bar.transform.SetParent(_panel.transform);
                bar.transform.localPosition = new Vector3(0, -0.52f, -0.01f);
                bar.transform.localScale = new Vector3(1.01f, 0.04f, 1.2f);
                Destroy(bar.GetComponent<Collider>());
                bar.GetComponent<Renderer>().material = new Material(shader)
                { color = SSColorPalette.Accent };


                var textObj = new GameObject("QuestionText");
                textObj.transform.SetParent(transform);
                textObj.transform.localPosition = new Vector3(0, 0.2f, -0.06f);
                textObj.transform.localRotation = Quaternion.identity;

                _questionText = textObj.AddComponent<ArabicTextMeshPro>();
                _questionText.alignment = TMPro.TextAlignmentOptions.Center;
                _questionText.color = Color.white;
                _questionText.fontStyle = TMPro.FontStyles.Bold;
                _questionText.enableAutoSizing = true;
                _questionText.fontSizeMin = 2f;
                _questionText.fontSizeMax = 5f;
                _questionText.rectTransform.sizeDelta = new Vector2(11f, 1.8f);
                _questionText.enableWordWrapping = true;
                _questionText.overflowMode = TMPro.TextOverflowModes.Ellipsis;
                SSFontManager.Apply(_questionText);


                var srcObj = new GameObject("SourceText");
                srcObj.transform.SetParent(transform);
                srcObj.transform.localPosition = new Vector3(0, -0.85f, -0.06f);
                srcObj.transform.localRotation = Quaternion.identity;

                _sourceText = srcObj.AddComponent<ArabicTextMeshPro>();
                _sourceText.alignment = TMPro.TextAlignmentOptions.Center;
                _sourceText.color = SSColorPalette.WithAlpha(Color.white, 0.5f);
                _sourceText.fontSize = 2f;
                _sourceText.rectTransform.sizeDelta = new Vector2(11f, 0.5f);
                SSFontManager.Apply(_sourceText);

            }

            _playerTransform = playerTarget;
            transform.localScale = Vector3.zero;
            _visible = false;

        }

        public void Show(string question, string source = "")
        {
            if (_questionText != null) _questionText.arabicText = question ?? "";
            if (_sourceText != null)
                _sourceText.arabicText = !string.IsNullOrEmpty(source) ? $"📖 {source}" : "";

            _visible = true;
            DOTween.Kill(transform, "displayScale");
            transform.DOScale(Vector3.one, 0.5f).SetEase(Ease.OutBack).SetId("displayScale");
        }
        public void ShowAnswers(string[] answers)
        {
            for (int i = 0; i < 4; i++)
            {
                AnswerTexts[i].arabicText = answers[i];
            }
        }
        private IEnumerator ReturnToBaseColor(int index)
        {
            yield return new WaitForSeconds(2.8f);
            print("Return for " + index);
            PanelRenderers[index].material.DOColor(_baseColor, 0.3f);
        }
        public void PlayCorrectAnimation(int index)
        {
            if (PanelRenderers != null) PanelRenderers[index].material.DOColor(SSColorPalette.GateCorrect, 0.3f);
            transform.DOPunchScale(Vector3.one * 0.2f, 0.5f, 8, 0.5f);
            if (AnswerTexts != null) AnswerTexts[index].transform.DOPunchScale(Vector3.one * 0.3f, 0.4f, 6, 0.3f);
            StartCoroutine(ReturnToBaseColor(index));
            print("Correct for " + index);
        }

        public void PlayWrongAnimation(int index)
        {
            if (PanelRenderers != null) PanelRenderers[index].material.DOColor(SSColorPalette.GateWrong, 0.3f);
            transform.DOShakePosition(0.5f, 0.4f, 20, 90f, false, true);
            transform.DOShakeRotation(0.5f, 10f, 20, 90f, true);
            StartCoroutine(ReturnToBaseColor(index));
            print("Wrong for " + index);
        }

        public void PlayRevealCorrect(int index)
        {
            if (PanelRenderers != null)
            {
                var seq = DOTween.Sequence();
                seq.Append(PanelRenderers[index].material.DOColor(SSColorPalette.GateCorrect, 0.2f));
                seq.Append(PanelRenderers[index].material.DOColor(SSColorPalette.Accent, 0.3f));
                seq.Append(PanelRenderers[index].material.DOColor(SSColorPalette.GateCorrect, 0.3f));
                seq.SetLoops(3, LoopType.Restart);
            }
            transform.DOPunchScale(Vector3.one * 0.15f, 0.8f, 4, 0.2f);
            StartCoroutine(ReturnToBaseColor(index));
            print("Reveal for " + index);
        }

        public void PlayFadeOut(int index)
        {
            /*
            if (_panelMaterial != null) _panelMaterial.DOFade(0.3f, 0.5f);
            */
            if (PanelRenderers != null) PanelRenderers[index].material.DOFade(0.3f, 0.5f);
            transform.DOScale(Vector3.one * 0.8f, 0.5f).SetEase(Ease.InBack);
            StartCoroutine(ReturnToBaseColor(index));
            print("Fade for " + index);
        }

        public void Show(McqQuestion question)
        {
            if (_questionText != null) _questionText.arabicText = question.question_text ?? "";
            if (_sourceText != null)
                _sourceText.arabicText = !string.IsNullOrEmpty(question.source) ? $"📖 {question.source}" : "";

            if (AnswerTexts.Length == 4)
            {
                AnswerTexts[0].arabicText = question.answer1;
                AnswerTexts[1].arabicText = question.answer2;
                AnswerTexts[2].arabicText = question.answer3;
                AnswerTexts[3].arabicText = question.answer4;
            }
            _visible = true;
            DOTween.Kill(transform, "displayScale");
            transform.DOScale(Vector3.one, 0.5f).SetEase(Ease.OutBack).SetId("displayScale");
        }

        public void Hide()
        {
            _visible = false;
            DOTween.Kill(transform, "displayScale");
            transform.DOScale(Vector3.zero, 0.3f).SetEase(Ease.InBack).SetId("displayScale");
        }

        private void LateUpdate()
        {
            if (_playerTransform == null) return;


            Vector3 targetPos = _playerTransform.position
                                + Vector3.up * floatHeight
                                + Vector3.forward * forwardOffset;
            transform.position = Vector3.Lerp(transform.position, targetPos,
                Time.deltaTime * followSpeed);


            if (Camera.main != null)
            {
                Vector3 awayFromCam = transform.position - Camera.main.transform.position;
                awayFromCam.y = 0;
                if (awayFromCam.sqrMagnitude > 0.001f)
                    transform.rotation = Quaternion.LookRotation(awayFromCam);
            }
        }
    }
}
