using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UIBuildingTooltip : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI description;
    [SerializeField] private TextMeshProUGUI buildOnTop;
    [SerializeField] private List<ImageTextPair> cost;

    private void Awake()
    {
        Events.OnShowTooltip += OnShowTooltip;
        Events.OnHideTooltip += OnHideTooltip;
        gameObject.SetActive(false);
    }

    private void OnDestroy()
    {
        Events.OnShowTooltip -= OnShowTooltip;
        Events.OnHideTooltip -= OnHideTooltip;
    }

    public void OnShowTooltip(BuildingData buildingData, Vector3 position)
    {
        transform.position = new Vector3(position.x, transform.position.y, transform.position.z);

        Vector3[] corners = new Vector3[4];
        gameObject.GetComponent<RectTransform>().GetWorldCorners(corners);
        Rect screenBounds = new Rect(0f, 0f, Screen.width, Screen.height);

        for (int i = 0; i < corners.Length; i++)
        {
            if (!screenBounds.Contains(corners[i]))
            {
                Vector3 corner = i switch
                {
                    0 => new Vector3(0, 0, 0),
                    1 => new Vector3(0, Screen.height, 0),
                    2 => new Vector3(Screen.width, Screen.height, 0),
                    3 => new Vector3(Screen.width, 0, 0),
                    _ => new Vector3(0, 0, 0),
                };

                Vector3 offset = corner - corners[i];

                transform.position += new Vector3(offset.x, 0, 0);
            }
        }

        description.text = buildingData.Description;
        buildOnTop.text = buildingData.CanPlaceOnTop ? "yes" : "no";

        for (int i = 0; i < buildingData.BuildingCost.Count; i++)
        {
            cost[i].Image.sprite = buildingData.BuildingCost[i].CardData.Prefab.GetComponent<SpriteRenderer>().sprite;
            cost[i].Text.text = buildingData.BuildingCost[i].Amount.ToString();
            cost[i].Image.gameObject.transform.parent.gameObject.SetActive(true);
        }

        for (int i = buildingData.BuildingCost.Count; i < cost.Count; i++)
        {
            cost[i].Image.gameObject.transform.parent.gameObject.SetActive(false);
        }

        gameObject.SetActive(true);
    }

    public void OnHideTooltip()
    {
        gameObject.SetActive(false);
    }

    [Serializable]
    class ImageTextPair
    {
        public Image Image;
        public TextMeshProUGUI Text;
    }
}
