using UnityEngine;
using System.Collections;
using UnityEngine.Events;

public class TvHandler : MonoBehaviour
{
    public static TvHandler Instance { get; private set; }

    public Animator animator;
    public GameObject minigameGanvas;
    public string[] channelStates;
    [Header("TV Screen Object")]
    public GameObject screen;  // Assign your TV screen here

    [Header("Break Settings")]
    public float maxOnTime = 10f;
    public GameObject sparks;

    private bool isOn = false;
    private bool isBroken = false;
    private Coroutine breakRoutine;

    public UnityEvent onBrokenEvent;

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Debug.LogWarning("[TvHandler] Multiple instances found. Destroying duplicate.");
            Destroy(this);
            return;
        }

        Instance = this;

        if (animator == null)
            animator = GetComponent<Animator>();
    }

    private void Start()
    {
        if (screen != null)
            screen.SetActive(false);
        else
            Debug.LogWarning("[TvHandler] Screen reference missing!");

        if (sparks != null)
            sparks.SetActive(false);
        else
            Debug.LogWarning("[TvHandler] Sparks reference missing!");
    }

    public bool PlayRandomChannel()
    {
        if (animator == null)
        {
            Debug.LogWarning("[TvHandler] Animator is missing!");
            return false;
        }

        if (channelStates == null || channelStates.Length == 0)
        {
            Debug.LogWarning("[TvHandler] No channel states assigned!");
            return false;
        }

        if(isBroken)
        {
            Debug.Log("TV is broken!! :(");
            return false;
        }

        if (!isOn)
        {
            TurnOnTV();
        }

        string randomChannel = channelStates[Random.Range(0, channelStates.Length)];

        if (!HasAnimationState(randomChannel))
        {
            Debug.LogWarning($"[TvHandler] Animator does not contain state: {randomChannel}");
            return false;
        }

        animator.Play(randomChannel);

        return true;
    }

    public void TurnOnTV()
    {
        if (isOn) return;

        isOn = true;
        if (screen != null)
            screen.SetActive(true);

        if (breakRoutine != null) StopCoroutine(breakRoutine);
        breakRoutine = StartCoroutine(BreakAfterTime());
    }

    public void TurnOffTV()
    {
        if (!isOn) return;

        isOn = false;
        if (screen != null)
            screen.SetActive(false);

        onBrokenEvent?.Invoke();
        if (breakRoutine != null)
        {
            StopCoroutine(breakRoutine);
            breakRoutine = null;
        }
    }

    private IEnumerator BreakAfterTime()
    {
        yield return new WaitForSeconds(maxOnTime);

        if (sparks != null)
            sparks.SetActive(true);
        isBroken = true;
        TurnOffTV();
        Debug.Log("TV broke after being on too long!");
    }

    public void RepairTV()
    {
        if (sparks != null)
            sparks.SetActive(false);
        isBroken = false;
    }

    private bool HasAnimationState(string stateName)
    {
        if (animator == null) return false;

        foreach (var clip in animator.runtimeAnimatorController.animationClips)
        {
            if (clip.name == stateName)
                return true;
        }
        return false;
    }

    private void OnMouseDown()
    {
        if(minigameGanvas && isBroken)
        {
            minigameGanvas.SetActive(true);
        }
    }

    public void CloseMiniGame(bool succeeded)
    {
        if (minigameGanvas)
        {
            minigameGanvas.SetActive(false);
            if(succeeded)
            {
                RepairTV();
            }
        }
    }
}
