using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using UnityEngine.InputSystem;
using System.Collections;

public class MapFullscreenVideo : MonoBehaviour
{
    private VideoPlayer videoPlayer;
    private RenderTexture renderTexture;
    private RawImage display;
    private CanvasGroup canvasGroup;
    private MapStep stepData;
    private System.Action onComplete;
    private bool canSkip = false;
    private bool hasCompleted = false;

    public void Initialize(MapStep step, System.Action onVideoComplete)
    {
        stepData = step;
        onComplete = onVideoComplete;

        Debug.Log($"[MapFullscreenVideo] Initialize - Video: {step.videoUrl}, Skipable: {step.skipable}, AutoAdvance: {step.autoAdvance}");

        canvasGroup = gameObject.AddComponent<CanvasGroup>();
        canvasGroup.alpha = 0f;

        CreateVideoPlayer();
        StartCoroutine(FadeInAndPlay());
    }

    void CreateVideoPlayer()
    {
        RectTransform rectTransform = GetComponent<RectTransform>();
        rectTransform.anchorMin = Vector2.zero;
        rectTransform.anchorMax = Vector2.one;
        rectTransform.offsetMin = Vector2.zero;
        rectTransform.offsetMax = Vector2.zero;

        GameObject bgObj = new GameObject("BlackBackground");
        bgObj.transform.SetParent(transform, false);
        RectTransform bgRect = bgObj.AddComponent<RectTransform>();
        bgRect.anchorMin = Vector2.zero;
        bgRect.anchorMax = Vector2.one;
        bgRect.offsetMin = Vector2.zero;
        bgRect.offsetMax = Vector2.zero;
        Image bgImage = bgObj.AddComponent<Image>();
        bgImage.color = Color.black;

        renderTexture = new RenderTexture(1920, 1080, 0);
        renderTexture.Create();

        GameObject videoPlayerObj = new GameObject("VideoPlayer");
        videoPlayerObj.transform.SetParent(transform, false);

        videoPlayer = videoPlayerObj.AddComponent<VideoPlayer>();
        videoPlayer.playOnAwake = false;
        videoPlayer.renderMode = VideoRenderMode.RenderTexture;
        videoPlayer.targetTexture = renderTexture;
        videoPlayer.isLooping = false;
        videoPlayer.aspectRatio = VideoAspectRatio.FitInside;
        videoPlayer.audioOutputMode = VideoAudioOutputMode.Direct;
        videoPlayer.url = stepData.videoUrl;

        GameObject displayObj = new GameObject("VideoDisplay");
        displayObj.transform.SetParent(transform, false);

        RectTransform displayRect = displayObj.AddComponent<RectTransform>();
        displayRect.anchorMin = Vector2.zero;
        displayRect.anchorMax = Vector2.one;
        displayRect.offsetMin = Vector2.zero;
        displayRect.offsetMax = Vector2.zero;

        display = displayObj.AddComponent<RawImage>();
        display.texture = renderTexture;
        display.color = Color.white;

        videoPlayer.loopPointReached += OnVideoFinished;
        videoPlayer.errorReceived += OnVideoError;
        videoPlayer.prepareCompleted += OnVideoPrepared;

        if (stepData.skipable)
        {
            CreateSkipButton();
        }

        Debug.Log("[MapFullscreenVideo] Preparing video...");
        videoPlayer.Prepare();
    }

    void OnVideoPrepared(VideoPlayer vp)
    {
        Debug.Log($"[MapFullscreenVideo] Video prepared - Duration: {vp.length}s, Frame Count: {vp.frameCount}");
    }

    void OnVideoError(VideoPlayer vp, string message)
    {
        Debug.LogError($"[MapFullscreenVideo] ERROR: {message}");
        // Si erreur, passer au step suivant quand même
        if (!hasCompleted)
        {
            hasCompleted = true;
            Debug.LogWarning("[MapFullscreenVideo] Skipping due to error");
            StartCoroutine(FadeOutAndFinish());
        }
    }

    void CreateSkipButton()
    {
        GameObject skipObj = new GameObject("SkipButton");
        skipObj.transform.SetParent(transform, false);

        RectTransform skipRect = skipObj.AddComponent<RectTransform>();
        skipRect.anchorMin = new Vector2(1f, 0f);
        skipRect.anchorMax = new Vector2(1f, 0f);
        skipRect.pivot = new Vector2(1f, 0f);
        skipRect.sizeDelta = new Vector2(200f, 60f);
        skipRect.anchoredPosition = new Vector2(-30f, 30f);

        Image skipBg = skipObj.AddComponent<Image>();
        skipBg.color = new Color(0f, 0f, 0f, 0.7f);

        Button skipButton = skipObj.AddComponent<Button>();
        skipButton.targetGraphic = skipBg;
        skipButton.onClick.AddListener(SkipVideo);

        GameObject textObj = new GameObject("Text");
        textObj.transform.SetParent(skipObj.transform, false);

        RectTransform textRect = textObj.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.offsetMin = Vector2.zero;
        textRect.offsetMax = Vector2.zero;

        TMPro.TextMeshProUGUI skipText = textObj.AddComponent<TMPro.TextMeshProUGUI>();
        skipText.text = "PASSER";
        skipText.fontSize = 20;
        skipText.alignment = TMPro.TextAlignmentOptions.Center;
        skipText.color = Color.white;

        Debug.Log("[MapFullscreenVideo] Skip button created");
    }

    IEnumerator FadeInAndPlay()
    {
        Debug.Log("[MapFullscreenVideo] Waiting for video to be prepared...");

        float timeout = 10f;
        float elapsed = 0f;

        while (!videoPlayer.isPrepared && elapsed < timeout)
        {
            elapsed += Time.deltaTime;
            yield return null;
        }

        if (!videoPlayer.isPrepared)
        {
            Debug.LogError("[MapFullscreenVideo] Video preparation timeout! Skipping...");
            if (!hasCompleted)
            {
                hasCompleted = true;
                StartCoroutine(FadeOutAndFinish());
            }
            yield break;
        }

        Debug.Log("[MapFullscreenVideo] Starting playback...");
        videoPlayer.Play();

        float fadeElapsed = 0f;
        float fadeTime = 0.5f;

        while (fadeElapsed < fadeTime)
        {
            fadeElapsed += Time.deltaTime;
            canvasGroup.alpha = Mathf.Lerp(0f, 1f, fadeElapsed / fadeTime);
            yield return null;
        }

        canvasGroup.alpha = 1f;
        canSkip = true;

        Debug.Log("[MapFullscreenVideo] Fade in complete, video playing");
    }

    void Update()
    {
        if (canSkip && stepData.skipable)
        {
            if (Keyboard.current != null && Keyboard.current.escapeKey.wasPressedThisFrame)
            {
                Debug.Log("[MapFullscreenVideo] User pressed Escape to skip");
                SkipVideo();
            }

            if (Mouse.current != null && Mouse.current.leftButton.wasPressedThisFrame)
            {
                Debug.Log("[MapFullscreenVideo] User clicked to skip");
                SkipVideo();
            }
        }

        // Debug info
        if (videoPlayer != null && videoPlayer.isPlaying)
        {
            // Log chaque 5 secondes
            if (Time.frameCount % 300 == 0)
            {
                Debug.Log($"[MapFullscreenVideo] Playing... {videoPlayer.time:F1}s / {videoPlayer.length:F1}s");
            }
        }
    }

    void SkipVideo()
    {
        if (!canSkip || hasCompleted) return;

        Debug.Log("[MapFullscreenVideo] SkipVideo called");
        canSkip = false;
        hasCompleted = true;
        StartCoroutine(FadeOutAndFinish());
    }

    void OnVideoFinished(VideoPlayer vp)
    {
        Debug.Log($"[MapFullscreenVideo] OnVideoFinished called - AutoAdvance: {stepData.autoAdvance}");

        if (hasCompleted)
        {
            Debug.LogWarning("[MapFullscreenVideo] Already completed, ignoring");
            return;
        }

        if (stepData.autoAdvance)
        {
            hasCompleted = true;
            Debug.Log("[MapFullscreenVideo] Auto-advancing to next step");
            StartCoroutine(FadeOutAndFinish());
        }
        else
        {
            Debug.Log("[MapFullscreenVideo] AutoAdvance is false, staying on video");
        }
    }

    IEnumerator FadeOutAndFinish()
    {
        Debug.Log("[MapFullscreenVideo] FadeOutAndFinish started");

        // IMPORTANT : Appeler le callback AVANT de détruire
        Debug.Log("[MapFullscreenVideo] Calling onComplete callback");
        onComplete?.Invoke();

        float elapsed = 0f;
        float fadeTime = 0.5f;

        while (elapsed < fadeTime)
        {
            elapsed += Time.deltaTime;
            canvasGroup.alpha = Mathf.Lerp(1f, 0f, elapsed / fadeTime);
            yield return null;
        }

        canvasGroup.alpha = 0f;

        if (videoPlayer != null && videoPlayer.isPlaying)
        {
            Debug.Log("[MapFullscreenVideo] Stopping video");
            videoPlayer.Stop();
        }

        Debug.Log("[MapFullscreenVideo] Destroying GameObject");
        Destroy(gameObject);
    }

    void OnDestroy()
    {
        Debug.Log("[MapFullscreenVideo] OnDestroy called");

        if (renderTexture != null)
        {
            renderTexture.Release();
            Destroy(renderTexture);
        }
    }
}