using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class DoorExit : MonoBehaviour
{
    public GameObject interactPrompt; // Assign your "Press E" text here

    public bool requiresKey = false;
    private bool doorOpen = true;
    public KeyAction key;

    private bool playerInRange = false;

    private bool entered = false;

    public SpriteRenderer[] doorBody;
    public Sprite[] closedDoor;
    public Sprite[] openDoor;

    private void Start()
    {
        interactPrompt.SetActive(false);
        if (requiresKey) CloseDoor();
    }

    private void CloseDoor()
    {
        doorOpen = false;
        for (int i = 0; i < doorBody.Length; i++)
        {
            doorBody[i].sprite = closedDoor[i];
        }
    }

    private void OpenDoor()
    {
        doorOpen = true;
        for (int i = 0; i < doorBody.Length; i++)
        {
            doorBody[i].sprite = openDoor[i];
        }
    }

    void Update()
    {
        if (entered) return;
        // If player is touching the door and presses 'E' (or your choice of key)
        if (playerInRange && Input.GetKeyDown(KeyCode.E) && doorOpen)
        {
            entered = true;
            StartCoroutine(EnterDoor());
            SoundManager.Instance.PlaySound("doorEnter", 2f);
        }
        else if (playerInRange && Input.GetKeyDown(KeyCode.E) && !doorOpen && key.isFollowing)
        {
            Destroy(key.gameObject);
            OpenDoor();
            SoundManager.Instance.PlaySound("doorOpen", 0.9f);
        }
    }

    private IEnumerator EnterDoor()
    {
        Time.timeScale = 0.0f;
        yield return new WaitForSecondsRealtime(0.8f);
        Time.timeScale = 1.0f;

        string name = SceneManager.GetActiveScene().name;
        string numberString = name.Replace("Level", "");

        if (int.TryParse(numberString, out int levelNumber))
        {
            int newLevel = levelNumber + 1;
            //Last level back to main menu
            if (newLevel == 17)
            {
                SceneManager.LoadScene("MainMenu");
            }
            else
            {
                SceneManager.LoadScene("Level" + newLevel);
            }
        }
    }

    // Detect when player is standing in front of the door
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            playerInRange = true;
            if (requiresKey && !key.isFollowing && !doorOpen) return;
            if (interactPrompt != null) interactPrompt.SetActive(true);
        }
    }

    // Detect when player walks away
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            playerInRange = false;
            if (interactPrompt != null) interactPrompt.SetActive(false);
        }
    }
}
