using MaskShop;
using System;
using System.Collections;
using Unity.Cinemachine;
using UnityEngine;
using UnityEngine.InputSystem;

public class UIManager : MonoBehaviour
{
    [Header("Screen de Transición")]
    [SerializeField] private CanvasGroup globalTransitionPanel;
    [SerializeField] private float transitionFadeDuration = 0.5f;
    [SerializeField] private float transitionHoldTime = 0.5f;
    private bool isTransitioning = false;

    [Header("Splash Screen de Estudio")]
    [SerializeField] private CanvasGroup cwStudioSplashScreen;
    [SerializeField] private CanvasGroup ggjSplashScreen;
    [SerializeField] private float studioSplashDuration = 3.0f;
    private CanvasGroup currentScreen;

    [Header("Configuración de Animación")]
    [SerializeField] private float fadeTime = 0.3f;
    [SerializeField] private LeanTweenType fadeEase = LeanTweenType.easeOutCubic;

    [Header("Pantallas (CanvasGroups)")]
    [SerializeField] private CanvasGroup initialScreen;
    [SerializeField] private CanvasGroup mainMenuCanvas;
    [SerializeField] private CanvasGroup inGameHUD;

    [Header("Directores de Cinemática")]
    [SerializeField] private UnityEngine.Playables.PlayableDirector introDirector;
    [SerializeField] private UnityEngine.Playables.PlayableDirector menuDirector;
    [SerializeField] private UnityEngine.Playables.PlayableDirector mainScreenDirector;

    [Header("Interacción de Usuario")]
    private InputAction anyButtonAction;
    [SerializeField] private RectTransform logoTransform;
    [SerializeField] private CanvasGroup pressAnyKeyText;
    [SerializeField] private CanvasGroup introSequenceCanvas;
    [SerializeField] private float logoBobAmount = 10f;
    [SerializeField] private float logoBobTime = 1.5f;
    [SerializeField] private float blinkMinAlpha = 0.3f;
    [SerializeField] private float blinkTime = 1.0f;

    [Header("Cámaras de Menú")]
    [SerializeField] private CinemachineCamera introCamera;
    [SerializeField] private CinemachineCamera mainMenuCamera;
    [SerializeField] private CinemachineCamera gameCamera;

    private bool isTitleScreenActive = false;
    private bool isAwaitingInput = false;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        CanvasGroup[] allScreens = GetComponentsInChildren<CanvasGroup>(true);
        foreach (CanvasGroup screen in allScreens)
        {
            if (screen == globalTransitionPanel) continue; // No ocultamos el panel de transición aún
            screen.alpha = 0;
            screen.interactable = false;
            screen.blocksRaycasts = false;
        }

        if (cwStudioSplashScreen != null)
        {
            ShowInstantScreen(cwStudioSplashScreen);
            currentScreen = cwStudioSplashScreen;
            StartCoroutine(WaitAndLoadStudioB(studioSplashDuration));
        }

        if (globalTransitionPanel != null)
        {
            globalTransitionPanel.alpha = 0;
            globalTransitionPanel.blocksRaycasts = false;
            globalTransitionPanel.gameObject.SetActive(true);
            globalTransitionPanel.transform.SetAsLastSibling();
        }

        anyButtonAction = new InputAction("PressAnyButton");
        anyButtonAction.AddBinding("<Keyboard>/anyKey");
        anyButtonAction.AddBinding("<Mouse>/leftButton");
        anyButtonAction.AddBinding("<Gamepad>/buttonSouth");
        anyButtonAction.AddBinding("<Gamepad>/start");
        anyButtonAction.Disable();

        if (introCamera != null) introCamera.Priority = 10;
        if (mainMenuCamera != null) mainMenuCamera.Priority = 9;
        if (gameCamera != null) gameCamera.Priority = 8;
        
    }
    // Update is called once per frame
    void Update()
    {
        if (isTransitioning) return;

        if (!GameManager.Instance.gameStarted && isAwaitingInput && anyButtonAction.WasPressedThisFrame())
        {
            GoToMainMenuScreen();
        }
    }
    private IEnumerator GlobalTransitionRoutine(Action middleLogicAction)
    {
        if (globalTransitionPanel == null)
        {
            middleLogicAction?.Invoke();
            yield break;
        }

        isTransitioning = true; // Bloquea inputs

        // Seguridad extra para traer al frente (Aunque recomiendo usar Canvas con Order 999)
        globalTransitionPanel.transform.SetAsLastSibling();
        globalTransitionPanel.blocksRaycasts = true; // Bloquea clicks

        // 1. FADE IN (Ir a negro)
        LeanTween.alphaCanvas(globalTransitionPanel, 1f, transitionFadeDuration)
            .setEase(LeanTweenType.easeOutQuad);

        // Esperamos a que termine el fade in
        yield return new WaitForSeconds(transitionFadeDuration);

        // 2. EJECUTAR LÓGICA (Cambiar pantallas mientras nadie ve nada)
        middleLogicAction?.Invoke();

        // 3. TIEMPO DE ESPERA EN NEGRO (HOLD TIME)
        // Aquí es donde la pantalla se queda negra el tiempo que definiste
        yield return new WaitForSeconds(transitionHoldTime);

        // 4. FADE OUT (Volver a transparente)
        LeanTween.alphaCanvas(globalTransitionPanel, 0f, transitionFadeDuration)
            .setEase(LeanTweenType.easeOutQuad);

        yield return new WaitForSeconds(transitionFadeDuration);

        // 5. Limpieza
        globalTransitionPanel.blocksRaycasts = false;
        isTransitioning = false; // Desbloquea inputs
    }

    private void ShowInstantScreen(CanvasGroup screen)
    {
        screen.gameObject.SetActive(true);
        screen.alpha = 1f;
        screen.interactable = true;
        screen.blocksRaycasts = true;
    }

    private IEnumerator WaitAndLoadStudioB(float duration)
    {
        yield return new WaitForSeconds(duration);
        if (ggjSplashScreen != null)
        {
            ggjSplashScreen.transform.SetAsLastSibling();
            ShowScreen(ggjSplashScreen);
            yield return new WaitForSeconds(fadeTime);
            //if (AudioManager.Instance != null) AudioManager.Play("cw");

            if (currentScreen != null)
            {
                currentScreen.alpha = 0f;
                currentScreen.gameObject.SetActive(false);
            }
            currentScreen = ggjSplashScreen;
            yield return new WaitForSeconds(studioSplashDuration);
            HideScreen(currentScreen);
            LoadTitleScreen();
        }
    }

    private void ShowScreen(CanvasGroup screen)
    {
        screen.gameObject.SetActive(true);
        LeanTween.alphaCanvas(screen, 1f, fadeTime).setEase(fadeEase);
        screen.interactable = true;
        screen.blocksRaycasts = true;
    }
    private void HideScreen(CanvasGroup screen)
    {
        LeanTween.alphaCanvas(screen, 0f, fadeTime).setEase(fadeEase);
        screen.interactable = false;
        screen.blocksRaycasts = false;
    }
    private void LoadTitleScreen()
    {
        LoadTitleScreenElements();
    }

    private void LoadTitleScreenElements()
    {
        if (GameManager.Instance != null)
        {
            GameManager.Instance.hasSeenIntro = true;
        }
        if (initialScreen != null)
        {
            ShowScreen(initialScreen);
            currentScreen = initialScreen;
            isTitleScreenActive = true;
            if (mainScreenDirector != null)
            {
                if (introDirector != null) introDirector.Stop();
                if (menuDirector != null) menuDirector.Stop();

                mainScreenDirector.Play();
            }
            /*if (AudioManager.Instance != null)
            {
                AudioManager.Instance.UnmuteMusic();
                AudioManager.PlayMusic(0, fadeTime);
            }*/

            anyButtonAction.Enable();
            isAwaitingInput = true;

            if (logoTransform != null)
            {
                float startY = logoTransform.anchoredPosition.y;
                LeanTween.moveY(logoTransform, startY + logoBobAmount, logoBobTime).setEase(LeanTweenType.easeInOutSine).setLoopPingPong();
            }
            if (pressAnyKeyText != null)
            {
                pressAnyKeyText.alpha = 1f;
                LeanTween.alphaCanvas(pressAnyKeyText, blinkMinAlpha, blinkTime).setEase(LeanTweenType.easeInOutSine).setLoopPingPong();
            }
        }
    }

    public void GoToMainMenuScreen()
    {
        if (isTransitioning) return;

        PlayTransition(() =>
        {
            if (mainMenuCanvas == null || currentScreen == mainMenuCanvas) return;

            if (currentScreen != null)
            {
                currentScreen.alpha = 0;
                currentScreen.interactable = false;
                currentScreen.blocksRaycasts = false;
            }

            if (menuDirector != null)
            {
                mainScreenDirector.Stop();
                introDirector.Stop();
                menuDirector.Play();
            }

            isTitleScreenActive = false;
            isAwaitingInput = false;
            anyButtonAction.Disable();

            if (logoTransform != null) LeanTween.cancel(logoTransform.gameObject);
            if (pressAnyKeyText != null) LeanTween.cancel(pressAnyKeyText.gameObject);

            ShowInstantScreen(mainMenuCanvas);
            currentScreen = mainMenuCanvas;

            if (mainMenuCamera != null) mainMenuCamera.Priority = 10;
            if (introCamera != null) introCamera.Priority = 9;

        });
    }
    public void StartGame()
    {
        if (isTransitioning) return;

        PlayTransition(() =>
        {
            if (mainMenuCanvas != null)
            {
                mainMenuCanvas.alpha = 0;
                mainMenuCanvas.interactable = false;
                mainMenuCanvas.blocksRaycasts = false;
            }

            if (introDirector != null)
            {
                menuDirector.Stop();
                mainScreenDirector.Stop();
                introDirector.Play();
            }
            else
            {
                FinishIntroAndStartGame();
            }
        });
    }
    public void FinishIntroAndStartGame()
    {
        if (introSequenceCanvas != null)
        {
            LeanTween.alphaCanvas(introSequenceCanvas, 0f, 0.5f).setOnComplete(() =>
            {
                introSequenceCanvas.gameObject.SetActive(false);
            });
        }
        BeginGameplayInternal();
    }
        private void BeginGameplayInternal()
    {
        isAwaitingInput = false;
        isTitleScreenActive = false;
        if (anyButtonAction != null) anyButtonAction.Disable();

        if (inGameHUD == null || gameCamera == null)
        {
            return;
        }

        GameManager.Instance.StartGameplay();

        /*if (AudioManager.Instance != null)
        {
            AudioManager.Instance.UnmuteMusic();
            AudioManager.PlayMusic(1, 2.0f);
        }*/

        if (currentScreen != null) HideScreen(currentScreen);
        ShowScreen(inGameHUD);
        currentScreen = inGameHUD;

        if(gameCamera != null) gameCamera.Priority = 10; 
        if(mainMenuCamera != null) mainMenuCamera.Priority = 9;
    }
    private void PlayTransition(Action action)
    {
        StartCoroutine(GlobalTransitionRoutine(action));
    }

}
