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

namespace com.al_arcade.tf
{
    using shared;

    public class TfQuestionScreen : MonoBehaviour
    {
        private ArabicTextMeshPro _questionText;
        private ArabicTextMeshPro _sourceText;
        private ArabicTextMeshPro _feedbackText;
        private Material _screenMat;
        private Material _feedbackMat;
        private GameObject _feedbackPanel;


        public void Build(Vector3 position, Vector3 cameraPos)
        {
            transform.position = position;
            var shader = GetShader();


            var frame = GameObject.CreatePrimitive(PrimitiveType.Cube);
            frame.name = "Frame";
            frame.transform.SetParent(transform);
            frame.transform.localPosition = Vector3.zero;
            frame.transform.localScale = new Vector3(7f, 3.5f, 0.2f);
            Destroy(frame.GetComponent<Collider>());
            frame.GetComponent<Renderer>().material =
                new Material(shader) { color = new Color32(25, 25, 35, 255) };


            var borderGlow = GameObject.CreatePrimitive(PrimitiveType.Cube);
            borderGlow.name = "BorderGlow";
            borderGlow.transform.SetParent(transform);
            borderGlow.transform.localPosition = new Vector3(0, 0, 0.01f);
            borderGlow.transform.localScale = new Vector3(7.15f, 3.65f, 0.18f);
            Destroy(borderGlow.GetComponent<Collider>());
            borderGlow.GetComponent<Renderer>().material =
                new Material(shader) { color = SSColorPalette.WithAlpha(SSColorPalette.Primary, 0.3f) };


            var surface = GameObject.CreatePrimitive(PrimitiveType.Cube);
            surface.name = "Surface";
            surface.transform.SetParent(transform);
            surface.transform.localPosition = new Vector3(0, 0, -0.12f);
            surface.transform.localScale = new Vector3(6.6f, 3.1f, 0.02f);
            Destroy(surface.GetComponent<Collider>());
            _screenMat = new Material(shader) { color = new Color32(15, 15, 50, 255) };
            surface.GetComponent<Renderer>().material = _screenMat;


            var pole = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
            pole.name = "Pole";
            pole.transform.SetParent(transform);
            pole.transform.localPosition = new Vector3(0, -3f, 0);
            pole.transform.localScale = new Vector3(0.12f, 1.8f, 0.12f);
            Destroy(pole.GetComponent<Collider>());
            pole.GetComponent<Renderer>().material =
                new Material(shader) { color = new Color32(70, 70, 85, 255) };


            var poleBase = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
            poleBase.name = "PoleBase";
            poleBase.transform.SetParent(transform);
            poleBase.transform.localPosition = new Vector3(0, -4.7f, 0);
            poleBase.transform.localScale = new Vector3(0.5f, 0.05f, 0.5f);
            Destroy(poleBase.GetComponent<Collider>());
            poleBase.GetComponent<Renderer>().material =
                new Material(shader) { color = new Color32(60, 60, 75, 255) };


            var textObj = new GameObject("QuestionText");
            textObj.transform.SetParent(transform);
            textObj.transform.localPosition = new Vector3(0, 0.25f, -0.25f);
            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 = 1.8f;
            _questionText.fontSizeMax = 3.8f;
            _questionText.rectTransform.sizeDelta = new Vector2(6.2f, 2.2f);
            _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, -1.15f, -0.25f);
            srcObj.transform.localRotation = Quaternion.identity;

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


            _feedbackPanel = GameObject.CreatePrimitive(PrimitiveType.Cube);
            _feedbackPanel.name = "FeedbackPanel";
            _feedbackPanel.transform.SetParent(transform);
            _feedbackPanel.transform.localPosition = new Vector3(0, 0, -0.2f);
            _feedbackPanel.transform.localScale = new Vector3(6.6f, 3.1f, 0.02f);
            Destroy(_feedbackPanel.GetComponent<Collider>());
            _feedbackMat = new Material(shader)
            {
                color = SSColorPalette.WithAlpha(SSColorPalette.Success, 0f)
            };
            _feedbackPanel.GetComponent<Renderer>().material = _feedbackMat;

            var fbObj = new GameObject("FeedbackText");
            fbObj.transform.SetParent(_feedbackPanel.transform);
            fbObj.transform.localPosition = new Vector3(0, 0, -0.15f);
            fbObj.transform.localRotation = Quaternion.identity;


            fbObj.transform.localScale = new Vector3(0.5f, 0.5f, 1f);

            _feedbackText = fbObj.AddComponent<ArabicTextMeshPro>();
            _feedbackText.alignment = TMPro.TextAlignmentOptions.Center;
            _feedbackText.color = Color.white;

            _feedbackText.fontSize = 4f;
            _feedbackText.fontSizeMin = 2.5f;
            _feedbackText.fontSizeMax = 5f;
            _feedbackText.enableAutoSizing = true;
            _feedbackText.fontStyle = TMPro.FontStyles.Bold;
            _feedbackText.rectTransform.sizeDelta = new Vector2(12f, 5f);
            _feedbackText.enableWordWrapping = true;
            _feedbackText.arabicText = "";
            SSFontManager.Apply(_feedbackText);


            var topStrip = GameObject.CreatePrimitive(PrimitiveType.Cube);
            topStrip.name = "TopStrip";
            topStrip.transform.SetParent(transform);
            topStrip.transform.localPosition = new Vector3(0, 1.8f, -0.12f);
            topStrip.transform.localScale = new Vector3(6.6f, 0.06f, 0.05f);
            Destroy(topStrip.GetComponent<Collider>());
            topStrip.GetComponent<Renderer>().material =
                new Material(shader) { color = SSColorPalette.Accent };

            var botStrip = GameObject.CreatePrimitive(PrimitiveType.Cube);
            botStrip.name = "BotStrip";
            botStrip.transform.SetParent(transform);
            botStrip.transform.localPosition = new Vector3(0, -1.8f, -0.12f);
            botStrip.transform.localScale = new Vector3(6.6f, 0.04f, 0.05f);
            Destroy(botStrip.GetComponent<Collider>());
            botStrip.GetComponent<Renderer>().material =
                new Material(shader) { color = SSColorPalette.WithAlpha(SSColorPalette.Accent, 0.5f) };


            for (int i = -1; i <= 1; i += 2)
            {
                var light = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                light.name = "StatusLight";
                light.transform.SetParent(frame.transform);
                light.transform.localPosition = new Vector3(i * 0.42f, -0.55f, -0.6f);
                light.transform.localScale = Vector3.one * 0.06f;
                Destroy(light.GetComponent<Collider>());
                light.GetComponent<Renderer>().material = new Material(shader)
                {
                    color = i < 0 ? SSColorPalette.TrueGreen : SSColorPalette.FalseRed
                };
            }


            Vector3 awayFromCamera = transform.position - cameraPos;
            awayFromCamera.y = 0;
            if (awayFromCamera.sqrMagnitude > 0.01f)
                transform.rotation = Quaternion.LookRotation(awayFromCamera);
        }


        public void ShowQuestion(string text, string source = "")
        {

            if (_feedbackMat != null)
            {
                DOTween.Kill(_feedbackMat, "fbMat");
                _feedbackMat.color = new Color(0, 0, 0, 0);
            }
            if (_feedbackText != null) _feedbackText.arabicText = "";

            if (_questionText != null)
            {
                _questionText.arabicText = text;
                DOTween.Kill(_questionText.transform, "qScale");
                _questionText.transform.localScale = Vector3.one * 0.6f;
                _questionText.DOFade(0, 0);
                _questionText.DOFade(1, 0.25f);
                _questionText.transform.DOScale(1f, 0.4f)
                    .SetEase(Ease.OutBack).SetId("qScale");
            }

            if (_sourceText != null)
                _sourceText.arabicText = !string.IsNullOrEmpty(source) ? $"📖 {source}" : "";


            if (_screenMat != null)
            {
                DOTween.Kill(_screenMat, "screenFlash");
                _screenMat
                    .DOColor(SSColorPalette.WithAlpha(SSColorPalette.Primary, 0.7f), 0.12f)
                    .SetId("screenFlash")
                    .OnComplete(() =>
                        _screenMat.DOColor(new Color32(15, 15, 50, 255), 0.35f));
            }
        }


        public void ShowFeedback(bool correct, int streak)
        {
            if (_feedbackText != null)
            {
                _feedbackText.arabicText = correct
                    ? (streak >= 3 ? $"🔥 ×{streak} ممتاز!" : "صحيح! ✓")
                    : "خطأ! ✗";

                DOTween.Kill(_feedbackText.transform, "fbScale");
                _feedbackText.transform.localScale = new Vector3(0.3f, 0.3f, 1f);
                _feedbackText.transform
                    .DOScale(new Vector3(0.5f, 0.5f, 1f), 0.3f)
                    .SetEase(Ease.OutBack).SetId("fbScale");
            }

            if (_feedbackMat != null)
            {
                DOTween.Kill(_feedbackMat, "fbMat");
                _feedbackMat.color = new Color(0, 0, 0, 0);
                Color target = SSColorPalette.WithAlpha(
                    correct ? SSColorPalette.Success : SSColorPalette.Danger, 0.82f);
                _feedbackMat.DOColor(target, 0.15f).SetId("fbMat");
            }
        }


        public void Clear()
        {
            if (_questionText != null) _questionText.arabicText = "";
            if (_sourceText != null) _sourceText.arabicText = "";
            if (_feedbackText != null) _feedbackText.arabicText = "";
            if (_feedbackMat != null)
            {
                DOTween.Kill(_feedbackMat, "fbMat");
                _feedbackMat.color = new Color(0, 0, 0, 0);
            }
        }

        private Shader GetShader() =>
            Shader.Find("Universal Render Pipeline/Lit")
            ?? Shader.Find("Standard") ?? Shader.Find("Unlit/Color");
    }
}
