using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine.UIElements;
using Toggle = UnityEngine.UI.Toggle;

public class MonsterRoom : Room
{
    [SerializeField] private GameObject numberTextObject;
    [SerializeField] private GameObject healthTickObject;
    [SerializeField] private int _health; // Number of times the room needs to be unlocked before becoming explored.

    private GameObject[] _healthTicks;
    protected override void InitializeRoom() {
        base.InitializeRoom();

        // Create the lock numbers on the room.
        numberTextObject.GetComponent<TextMeshProUGUI>().text = ((NumberLock)_locks[0]).GetNumber().ToString();
        GameObject lockToDuplicate = numberTextObject;
        for (int i = 1; i < _locks.Length; i++)
        {
            lockToDuplicate = DuplicateToTheLeft(lockToDuplicate, ((RectTransform)lockToDuplicate.transform).rect.width);
            lockToDuplicate.GetComponent<TextMeshProUGUI>().text = ((NumberLock)_locks[i]).GetNumber().ToString();
        }

        _healthTicks = new GameObject[_health];
        _healthTicks[0] = healthTickObject;
        for (int i = 1; i < _health; i++)
        {
            _healthTicks[i] = DuplicateDown(_healthTicks[i - 1],
                ((RectTransform)_healthTicks[i - 1].transform).rect.height);
        }
    }

    public override bool TryUnlock(DicePair pair) {
        foreach (NumberLock numberLock in _locks)
        {
            if (numberLock.CheckIfKeyFits(pair))
            {
                return true;
            }
        }

        return false;
    }

    public override void SetRoomExplored()
    {
        _healthTicks[^_health].GetComponent<Toggle>().isOn = true; // Toggles the corresponding health tick
        _health -= 1;
        if (_health == 0)
        {
            _isExplored = true;
            UnhighlightRoomAsOption();
            if (roomReward != null)
            {
                roomReward.TriggerGetReward();
            }
            gameObject.GetComponent<SpriteRenderer>().color =
                ColorHelper.AddColorTint(gameObject.GetComponent<SpriteRenderer>().color, Color.grey, 0.5f);
        }
    }

    private GameObject DuplicateToTheLeft(GameObject original, float offset) {
        GameObject clone = Instantiate(original, original.transform.parent);
        clone.transform.localPosition -= new Vector3(offset, 0, 0);
        return clone;
    }

    private GameObject DuplicateDown(GameObject original, float offset)
    {
        GameObject clone = Instantiate(original, original.transform.parent);
        clone.transform.localPosition -= new Vector3(0, offset, 0);
        return clone;
    }
}
