using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using DG.Tweening;
using TMPro;

namespace com.al_arcade.cs
{
    using shared;
    using UnityEngine.Rendering.Universal;

    [AddComponentMenu("Science Street/CS Prefab Builder")]
    public class CsPrefabBuilder : MonoBehaviour
    {


        [Header("Scene Environment")]
        [Tooltip("Your full environment prefab (ground, platform, decorations, etc). Spawned at origin.")]
        [SerializeField] private GameObject environmentPrefab;

        [Header("Camera")]
        [Tooltip("Leave null to use Camera.main with default settings.")]
        [SerializeField] private Camera cameraOverride;
        [SerializeField] private Vector3 cameraPosition = new Vector3(0, 4f, -6f);
        [SerializeField] private Vector3 cameraRotation = new Vector3(25, 0, 0);
        [SerializeField] private float cameraFOV = 60f;
        [SerializeField] private Color cameraBgColor = new Color32(30, 30, 60, 255);


        [Header("Lighting (leave null to skip)")]
        [Tooltip("Drag in your own directional light prefab, or leave null to auto-create.")]
        [SerializeField] private GameObject directionalLightPrefab;
        [SerializeField] private GameObject[] extraLightPrefabs;
        [SerializeField] private Color ambientColor = new Color32(40, 42, 60, 255);


        [Header("Bot")]
        [Tooltip("Your bot prefab. MUST have CsBotController attached.\n" +
                 "If null, a procedural bot is created.")]
        [SerializeField] private GameObject botPrefab;
        [SerializeField] private Vector3 botSpawnPosition = Vector3.zero;
        [SerializeField] private Quaternion botSpawnRotation = Quaternion.identity;



        [Header("Word Card (optional)")]
        [Tooltip("A prefab for the word card. MUST have CsWordButton.\n" +
                 "If null, the default procedural card is used.")]
        [SerializeField] private GameObject wordCardPrefab;


        [Header("UI Canvas")]
        [Tooltip("Your Canvas prefab. MUST have CsUIManager with ALL internal " +
                 "references wired in the inspector.\n" +
                 "If null, a procedural UI is created.")]
        [SerializeField] private GameObject canvasPrefab;


        [Header("Audio — SFX Clips (all optional)")]
        [SerializeField] private AudioClip sfxCorrect;
        [SerializeField] private AudioClip sfxWrong;
        [SerializeField] private AudioClip sfxClick;
        [SerializeField] private AudioClip sfxVictory;
        [SerializeField] private AudioClip sfxDefeat;
        [SerializeField] private AudioClip sfxWhoosh;
        [SerializeField] private AudioClip sfxPop;
        [SerializeField] private AudioClip sfxSlam;
        [SerializeField] private AudioClip sfxCheer;


        [Header("Particles (all optional)")]
        [SerializeField] private ParticleSystem correctBurstParticle;
        [SerializeField] private ParticleSystem wrongBurstParticle;
        [SerializeField] private ParticleSystem confettiParticle;
        [SerializeField] private ParticleSystem sparksParticle;
        [SerializeField] private ParticleSystem starBurstParticle;


        [Header("Arabic Font")]
        [SerializeField] private TMP_FontAsset arabicFont;


        [Header("Game Settings")]
        [SerializeField] private string buildType = "scistreet";
        [SerializeField] private int gradeId = 0;
        [SerializeField] private int questionCount = 8;
        [SerializeField] private string classCode = "";

        [Header("Debug")]
        [SerializeField] private bool useOfflineTestData = false;


        private CsGameManager _gm;
        private CsBotController _bot;
        private CsUIManager _uiManager;


        private void Start()
        {
            DOTween.Init();
            if (arabicFont != null) SSFontManager.Font = arabicFont;
            StartCoroutine(BuildEverything());
        }

        private IEnumerator BuildEverything()
        {
            Debug.Log("═══ CS Prefab Builder — Starting ═══");


            if (FindObjectOfType<EventSystem>() == null)
            {
                var es = new GameObject("EventSystem");
                es.AddComponent<EventSystem>();
                es.AddComponent<StandaloneInputModule>();
            }


            SSApiManager.EnsureInstance();
            SetupAudioManager();
            SetupParticleManager();

            var session = SSGameSession.EnsureInstance();
            session.buildType = buildType;
            session.gradeId = gradeId;
            session.questionCount = questionCount;
            session.classCode = classCode;
            yield return null;


            SetupCamera();
            yield return null;


            if (environmentPrefab != null)
                Instantiate(environmentPrefab, Vector3.zero, Quaternion.identity);
            yield return null;


            SetupLighting();
            yield return null;


            if (botPrefab != null)
            {
                var botObj = Instantiate(botPrefab, botSpawnPosition, botSpawnRotation);
                botObj.name = "Bot";
                _bot = botObj.GetComponent<CsBotController>();
                if (_bot == null)
                {
                    Debug.LogError("[CS] Bot prefab is missing CsBotController!");
                    yield break;
                }


            }
            else
            {

                var botObj = new GameObject("Bot");
                botObj.transform.position = botSpawnPosition;
                _bot = botObj.AddComponent<CsBotController>();
                _bot.Build();
            }
            yield return null;


            var wordContainer = new GameObject("WordContainer");
            wordContainer.transform.position = Vector3.zero;
            yield return null;


            if (canvasPrefab != null)
            {
                var canvasObj = Instantiate(canvasPrefab);
                canvasObj.name = "CsUI";
                _uiManager = canvasObj.GetComponentInChildren<CsUIManager>();
                if (_uiManager == null)
                {
                    Debug.LogError("[CS] Canvas prefab is missing CsUIManager!");
                    yield break;
                }

            }
            else
            {

                var uiObj = new GameObject("CsUI");
                _uiManager = uiObj.AddComponent<CsUIManager>();
                _uiManager.BuildUI();
            }

            if (_uiManager.onRestartClicked == null)
                _uiManager.onRestartClicked = new UnityEvent();
            yield return null;


            var gmObj = new GameObject("CsGameManager");
            _gm = gmObj.AddComponent<CsGameManager>();
            _gm.bot = _bot;
            _gm.uiManager = _uiManager;
            _gm.wordContainer = wordContainer.transform;
            _uiManager.onRestartClicked.AddListener(OnRestartClicked);
            yield return null;

            Debug.Log("═══ CS Game built! Starting... ═══");
            yield return new WaitForSeconds(0.5f);

            if (useOfflineTestData)
                _gm.StartWithQuestions(GetTestQuestions());
            else
                _gm.StartGame();
        }


        private void SetupCamera()
        {
            var cam = cameraOverride != null ? cameraOverride : Camera.main;
            if (cam == null) return;
            cam.clearFlags = CameraClearFlags.SolidColor;
            cam.backgroundColor = cameraBgColor;
            cam.transform.position = cameraPosition;

            var cameraData = cam.GetUniversalAdditionalCameraData();
            cameraData.renderPostProcessing = true;
            cameraData.antialiasing = AntialiasingMode.SubpixelMorphologicalAntiAliasing;
            cameraData.antialiasingQuality = AntialiasingQuality.High;

            cam.transform.rotation = Quaternion.Euler(cameraRotation);
            cam.fieldOfView = cameraFOV;
            cam.nearClipPlane = 0.1f;
        }

        private void SetupLighting()
        {
            if (directionalLightPrefab != null)
                Instantiate(directionalLightPrefab);

            if (extraLightPrefabs != null)
            {
                foreach (var lp in extraLightPrefabs)
                    if (lp != null) Instantiate(lp);
            }

            RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat;
            RenderSettings.ambientLight = ambientColor;
        }

        private void SetupAudioManager()
        {
            var audio = SSAudioManager.EnsureInstance();
            if (sfxCorrect != null) audio.sfxCorrect = sfxCorrect;
            if (sfxWrong != null) audio.sfxWrong = sfxWrong;
            if (sfxClick != null) audio.sfxClick = sfxClick;
            if (sfxVictory != null) audio.sfxVictory = sfxVictory;
            if (sfxDefeat != null) audio.sfxDefeat = sfxDefeat;
            if (sfxWhoosh != null) audio.sfxWhoosh = sfxWhoosh;
            if (sfxPop != null) audio.sfxPop = sfxPop;
            if (sfxSlam != null) audio.sfxSlam = sfxSlam;
            if (sfxCheer != null) audio.sfxCheer = sfxCheer;
        }

        private void SetupParticleManager()
        {
            var particles = SSParticleManager.EnsureInstance();
            if (correctBurstParticle != null) particles.correctBurstPrefab = correctBurstParticle;
            if (wrongBurstParticle != null) particles.wrongBurstPrefab = wrongBurstParticle;
            if (confettiParticle != null) particles.confettiPrefab = confettiParticle;
            if (sparksParticle != null) particles.sparksPrefab = sparksParticle;
            if (starBurstParticle != null) particles.starBurstPrefab = starBurstParticle;
        }

        private void OnRestartClicked()
        {
            if (_gm != null) _gm.ResetGame();
            if (_gm != null) _gm.StartGame();
        }


        private CsQuestion[] GetTestQuestions()
        {
            return new CsQuestion[]
            {
                new()
                {
                    id = "1", source = "علوم",
                    wrong_word = "القمر", correct_answer = "الشمس",
                    words = new CsWord[]
                    {
                        new() { word_text = "القمر",    position = 0, is_wrong = true  },
                        new() { word_text = "مصدر",     position = 1, is_wrong = false },
                        new() { word_text = "الضوء",    position = 2, is_wrong = false },
                        new() { word_text = "والحرارة", position = 3, is_wrong = false },
                        new() { word_text = "للأرض",    position = 4, is_wrong = false },
                    },
                    options = new CsOption[]
                    {
                        new() { option_text = "الشمس",   is_correct = true  },
                        new() { option_text = "النجوم",   is_correct = false },
                        new() { option_text = "الكواكب",  is_correct = false },
                    }
                },
                new()
                {
                    id = "2", source = "جغرافيا",
                    wrong_word = "خمس", correct_answer = "سبع",
                    words = new CsWord[]
                    {
                        new() { word_text = "يتكون", position = 0, is_wrong = false },
                        new() { word_text = "العالم", position = 1, is_wrong = false },
                        new() { word_text = "من",     position = 2, is_wrong = false },
                        new() { word_text = "خمس",    position = 3, is_wrong = true  },
                        new() { word_text = "قارات",  position = 4, is_wrong = false },
                    },
                    options = new CsOption[]
                    {
                        new() { option_text = "ست",  is_correct = false },
                        new() { option_text = "سبع", is_correct = true  },
                        new() { option_text = "ثمان", is_correct = false },
                    }
                },
            };
        }
    }
}
