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

namespace com.al_arcade.tf
{
    using shared;

    public class TfUIManager : MonoBehaviour
    {
        private Canvas _canvas;
        private CanvasGroup _gameUI, _loadingUI, _errorUI, _resultsUI;
        private ArabicTextMeshProUGUI _scoreText, _streakText;
        private ArabicTextMeshProUGUI _loadingText, _errorText;
        private Image _progressFill;
        private ArabicTextMeshProUGUI _progressLabel;
        private ArabicTextMeshProUGUI _resultTitle, _resultScore, _resultStats;

        [Header("Events")]
        public UnityEvent onRestartClicked;


        public void BuildUI()
        {
            var co = new GameObject("TfCanvas");
            co.transform.SetParent(transform);
            _canvas = co.AddComponent<Canvas>();
            _canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            _canvas.sortingOrder = 100;

            var sc = co.AddComponent<CanvasScaler>();
            sc.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            sc.referenceResolution = new Vector2(1920, 1080);
            sc.matchWidthOrHeight = 0.5f;
            co.AddComponent<GraphicRaycaster>();

            BuildGameHUD(co.transform);
            BuildLoadingPanel(co.transform);
            BuildErrorPanel(co.transform);
            BuildResultsPanel(co.transform);

            _gameUI.alpha = 0; _gameUI.gameObject.SetActive(false);
            _loadingUI.alpha = 0; _loadingUI.gameObject.SetActive(false);
            _errorUI.alpha = 0; _errorUI.gameObject.SetActive(false);
            _resultsUI.alpha = 0; _resultsUI.gameObject.SetActive(false);
        }


        private void BuildGameHUD(Transform parent)
        {
            var go = MkPanel(parent, "GameUI");
            _gameUI = go.AddComponent<CanvasGroup>();


            var topBarObj = new GameObject("TopBar");
            topBarObj.transform.SetParent(go.transform, false);
            var tbr = topBarObj.AddComponent<RectTransform>();
            tbr.anchorMin = new Vector2(0, 1);
            tbr.anchorMax = new Vector2(1, 1);
            tbr.pivot = new Vector2(0.5f, 1);
            tbr.anchoredPosition = Vector2.zero;
            tbr.sizeDelta = new Vector2(0, 72);
            topBarObj.AddComponent<Image>().color =
                SSColorPalette.WithAlpha(SSColorPalette.PrimaryDark, 0.82f);


            _scoreText = MkTxt(topBarObj.transform, "Score", "0",
                32, new Vector2(0, 0.5f), new Vector2(36, 6), new Vector2(180, 44));
            _scoreText.color = SSColorPalette.Accent;
            _scoreText.fontStyle = TMPro.FontStyles.Bold;
            _scoreText.alignment = TMPro.TextAlignmentOptions.MidlineLeft;


            var scoreLbl = MkTxt(topBarObj.transform, "ScoreLbl", "النقاط",
                14, new Vector2(0, 0.5f), new Vector2(36, -20), new Vector2(100, 22));
            scoreLbl.color = SSColorPalette.WithAlpha(Color.white, 0.5f);
            scoreLbl.alignment = TMPro.TextAlignmentOptions.MidlineLeft;


            _streakText = MkTxt(topBarObj.transform, "Streak", "",
                26, new Vector2(0.5f, 0.5f), new Vector2(0, 0), new Vector2(200, 44));
            _streakText.color = SSColorPalette.Warning;
            _streakText.alignment = TMPro.TextAlignmentOptions.Center;


            var progBg = new GameObject("ProgressBg");
            progBg.transform.SetParent(go.transform, false);
            var pr = progBg.AddComponent<RectTransform>();
            pr.anchorMin = new Vector2(0.28f, 1);
            pr.anchorMax = new Vector2(0.72f, 1);
            pr.pivot = new Vector2(0.5f, 1);
            pr.anchoredPosition = new Vector2(0, -78);
            pr.sizeDelta = new Vector2(0, 14);
            var progBgImg = progBg.AddComponent<Image>();
            progBgImg.color = SSColorPalette.WithAlpha(Color.white, 0.08f);

            var fill = new GameObject("Fill");
            fill.transform.SetParent(progBg.transform, false);
            var fr = fill.AddComponent<RectTransform>();
            fr.anchorMin = Vector2.zero;
            fr.anchorMax = new Vector2(0, 1);
            fr.pivot = new Vector2(0, 0.5f);
            fr.offsetMin = Vector2.zero;
            fr.offsetMax = Vector2.zero;
            _progressFill = fill.AddComponent<Image>();
            _progressFill.color = SSColorPalette.Accent;


            _progressLabel = MkTxt(go.transform, "ProgLbl", "0 / 5",
                16, new Vector2(0.5f, 1), new Vector2(0, -98), new Vector2(200, 22));
            _progressLabel.alignment = TMPro.TextAlignmentOptions.Center;
            _progressLabel.color = SSColorPalette.WithAlpha(Color.white, 0.55f);


            var hintObj = new GameObject("HintBg");
            hintObj.transform.SetParent(go.transform, false);
            var hbr = hintObj.AddComponent<RectTransform>();
            hbr.anchorMin = new Vector2(0.25f, 0);
            hbr.anchorMax = new Vector2(0.75f, 0);
            hbr.pivot = new Vector2(0.5f, 0);
            hbr.anchoredPosition = new Vector2(0, 20);
            hbr.sizeDelta = new Vector2(0, 44);
            var hintBgImg = hintObj.AddComponent<Image>();
            hintBgImg.color = SSColorPalette.WithAlpha(SSColorPalette.PrimaryDark, 0.6f);

            var hint = MkTxt(hintObj.transform, "Hint",
                "← صح (يسار)  |  خطأ (يمين) →",
                18, new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(480, 36));
            hint.alignment = TMPro.TextAlignmentOptions.Center;
            hint.color = SSColorPalette.WithAlpha(Color.white, 0.5f);
        }


        private void BuildLoadingPanel(Transform parent)
        {
            var go = MkPanel(parent, "LoadingUI");
            _loadingUI = go.AddComponent<CanvasGroup>();
            go.AddComponent<Image>().color =
                SSColorPalette.WithAlpha(SSColorPalette.PrimaryDark, 0.9f);

            _loadingText = MkTxt(go.transform, "Txt", "جاري التحميل...",
                28, new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(500, 50));
            _loadingText.alignment = TMPro.TextAlignmentOptions.Center;
            _loadingText.color = Color.white;


            var dots = MkTxt(go.transform, "Dots", "● ● ●",
                18, new Vector2(0.5f, 0.5f), new Vector2(0, -36), new Vector2(200, 30));
            dots.alignment = TMPro.TextAlignmentOptions.Center;
            dots.color = SSColorPalette.Accent;
        }


        private void BuildErrorPanel(Transform parent)
        {
            var go = MkPanel(parent, "ErrorUI");
            _errorUI = go.AddComponent<CanvasGroup>();
            go.AddComponent<Image>().color =
                SSColorPalette.WithAlpha(SSColorPalette.Danger, 0.9f);

            _errorText = MkTxt(go.transform, "Txt", "خطأ",
                24, new Vector2(0.5f, 0.5f), Vector2.zero, new Vector2(600, 90));
            _errorText.alignment = TMPro.TextAlignmentOptions.Center;
            _errorText.color = Color.white;
            _errorText.enableWordWrapping = true;
        }


        private void BuildResultsPanel(Transform parent)
        {
            var go = MkPanel(parent, "ResultsUI");
            _resultsUI = go.AddComponent<CanvasGroup>();


            var bg = go.AddComponent<Image>();
            bg.color = SSColorPalette.WithAlpha(SSColorPalette.PrimaryDark, 0.94f);


            var card = new GameObject("Card");
            card.transform.SetParent(go.transform, false);
            var cr = card.AddComponent<RectTransform>();
            cr.anchorMin = new Vector2(0.25f, 0.15f);
            cr.anchorMax = new Vector2(0.75f, 0.85f);
            cr.offsetMin = cr.offsetMax = Vector2.zero;
            var cardImg = card.AddComponent<Image>();
            cardImg.color = SSColorPalette.WithAlpha(new Color32(30, 30, 55, 255), 0.95f);


            _resultTitle = MkTxt(card.transform, "Title", "تم التصنيع! 🎉",
                42, new Vector2(0.5f, 1), new Vector2(0, -50), new Vector2(500, 55));
            _resultTitle.alignment = TMPro.TextAlignmentOptions.Center;
            _resultTitle.color = SSColorPalette.Accent;
            _resultTitle.fontStyle = TMPro.FontStyles.Bold;


            _resultScore = MkTxt(card.transform, "Score", "0",
                56, new Vector2(0.5f, 1), new Vector2(0, -130), new Vector2(300, 70));
            _resultScore.alignment = TMPro.TextAlignmentOptions.Center;
            _resultScore.color = Color.white;
            _resultScore.fontStyle = TMPro.FontStyles.Bold;


            MkTxt(card.transform, "ScoreLbl", "النقاط",
                16, new Vector2(0.5f, 1), new Vector2(0, -185), new Vector2(100, 25))
                .color = SSColorPalette.WithAlpha(Color.white, 0.4f);


            _resultStats = MkTxt(card.transform, "Stats", "",
                20, new Vector2(0.5f, 0.5f), new Vector2(0, 10), new Vector2(450, 60));
            _resultStats.alignment = TMPro.TextAlignmentOptions.Center;
            _resultStats.color = SSColorPalette.WithAlpha(Color.white, 0.65f);
            _resultStats.enableWordWrapping = true;


            var btnObj = new GameObject("RestartBtn");
            btnObj.transform.SetParent(card.transform, false);
            var br = btnObj.AddComponent<RectTransform>();
            br.anchorMin = new Vector2(0.5f, 0);
            br.anchorMax = new Vector2(0.5f, 0);
            br.pivot = new Vector2(0.5f, 0);
            br.anchoredPosition = new Vector2(0, 40);
            br.sizeDelta = new Vector2(260, 52);

            var btnImg = btnObj.AddComponent<Image>();
            btnImg.color = SSColorPalette.Accent;

            var btn = btnObj.AddComponent<Button>();
            btn.onClick.AddListener(() =>
            {
                _resultsUI.DOFade(0, 0.3f)
                    .OnComplete(() => _resultsUI.gameObject.SetActive(false));
                onRestartClicked?.Invoke();
            });

            var btnTxt = MkTxt(btnObj.transform, "BtnTxt", "إعادة اللعب 🔄",
                22, Vector2.zero, Vector2.zero, Vector2.zero);
            btnTxt.rectTransform.anchorMin = Vector2.zero;
            btnTxt.rectTransform.anchorMax = Vector2.one;
            btnTxt.rectTransform.offsetMin = btnTxt.rectTransform.offsetMax = Vector2.zero;
            btnTxt.alignment = TMPro.TextAlignmentOptions.Center;
            btnTxt.color = SSColorPalette.TextDark;
            btnTxt.fontStyle = TMPro.FontStyles.Bold;
        }


        public void ShowGameUI()
        {
            _gameUI.gameObject.SetActive(true);
            _gameUI.DOFade(1, 0.3f);
        }

        public void SetScore(int s)
        {
            if (_scoreText == null) return;
            _scoreText.arabicText = s.ToString("N0");
            DOTween.Kill(_scoreText.transform, "sp");
            _scoreText.transform.DOPunchScale(Vector3.one * 0.12f, 0.2f, 4, 0.2f).SetId("sp");
        }

        public void SetStreak(int s)
        {
            if (_streakText == null) return;
            _streakText.arabicText = s > 1 ? $"🔥 ×{s}" : "";
            if (s > 1)
            {
                DOTween.Kill(_streakText.transform, "sk");
                _streakText.transform.localScale = Vector3.one * 1.4f;
                _streakText.transform.DOScale(1f, 0.35f).SetEase(Ease.OutElastic).SetId("sk");
            }
        }

        public void SetProgress(int cur, int total)
        {
            if (_progressLabel != null) _progressLabel.arabicText = $"{cur} / {total}";
            if (_progressFill != null && total > 0)
            {
                DOTween.Kill(_progressFill.rectTransform, "pf");
                _progressFill.rectTransform
                    .DOAnchorMax(new Vector2((float)cur / total, 1), 0.4f)
                    .SetEase(Ease.OutQuad).SetId("pf");
            }
        }

        public void ShowLoading(string m)
        {
            _loadingUI.gameObject.SetActive(true);
            if (_loadingText != null) _loadingText.arabicText = m;
            _loadingUI.DOFade(1, 0.3f);
        }

        public void HideLoading()
        {
            _loadingUI.DOFade(0, 0.3f)
                .OnComplete(() => _loadingUI.gameObject.SetActive(false));
        }

        public void ShowError(string m)
        {
            _errorUI.gameObject.SetActive(true);
            if (_errorText != null) _errorText.arabicText = m;
            _errorUI.DOFade(1, 0.3f);
        }

        public void ShowResults(int score, int correct, int wrong, bool won)
        {
            _resultsUI.gameObject.SetActive(true);
            _resultsUI.alpha = 0;

            if (_resultTitle != null)
                _resultTitle.arabicText = won ? "تم التصنيع بنجاح! 🎉" : "حظ أوفر! 😔";
            if (_resultScore != null)
                _resultScore.arabicText = score.ToString("N0");
            if (_resultStats != null)
                _resultStats.arabicText = $"✓ صحيح: {correct}  |  ✗ خطأ: {wrong}";


            var seq = DOTween.Sequence();
            seq.Append(_resultsUI.DOFade(1, 0.4f));
            if (_resultTitle != null)
            {
                _resultTitle.transform.localScale = Vector3.zero;
                seq.Append(_resultTitle.transform
                    .DOScale(1, 0.45f).SetEase(Ease.OutBack));
            }
            if (_resultScore != null)
            {
                _resultScore.transform.localScale = Vector3.zero;
                seq.Append(_resultScore.transform
                    .DOScale(1, 0.35f).SetEase(Ease.OutBack));


                int ds = 0;
                DOTween.To(() => ds, x =>
                {
                    ds = x;
                    if (_resultScore != null) _resultScore.arabicText = x.ToString("N0");
                }, score, 1f).SetEase(Ease.OutQuad).SetDelay(0.7f);
            }
        }

        public void ResetUI()
        {
            if (_gameUI != null) _gameUI.gameObject.SetActive(false);
            if (_loadingUI != null) _loadingUI.gameObject.SetActive(false);
            if (_errorUI != null) _errorUI.gameObject.SetActive(false);
            if (_resultsUI != null) _resultsUI.gameObject.SetActive(false);
        }


        private GameObject MkPanel(Transform p, string n)
        {
            var go = new GameObject(n);
            go.transform.SetParent(p, false);
            var r = go.AddComponent<RectTransform>();
            r.anchorMin = Vector2.zero;
            r.anchorMax = Vector2.one;
            r.sizeDelta = Vector2.zero;
            return go;
        }

        private ArabicTextMeshProUGUI MkTxt(Transform p, string n, string text,
            float size, Vector2 anchor, Vector2 pos, Vector2 sz)
        {
            var go = new GameObject(n);
            go.transform.SetParent(p, false);
            var r = go.AddComponent<RectTransform>();
            r.anchorMin = r.anchorMax = anchor;
            r.pivot = anchor;
            r.anchoredPosition = pos;
            r.sizeDelta = sz;
            var t = go.AddComponent<ArabicTextMeshProUGUI>();
            t.arabicText = text;
            t.fontSize = size;
            t.enableWordWrapping = true;
            SSFontManager.Apply(t);
            return t;
        }
    }
}
