using UnityEngine;
using UnityEngine.UIElements;
using System;

public enum BuildingType
{
    Shop,
    AdventurersGuild,
    Harbor,
    Inn,
    House,
    Other
}

[System.Serializable]
public class TownBuilding : MonoBehaviour
{
    [Header("Building Configuration")]
    public string buildingName = "Building";
    public BuildingType buildingType = BuildingType.Other;
    public Sprite buildingIcon;
    public string description = "A building in the town";

    [Header("Visual Settings")]
    public Vector2Int gridPosition = Vector2Int.zero;
    public Vector2Int buildingSize = Vector2Int.one;
    public Color buildingColor = Color.white;

    [Header("Interaction")]
    public bool isInteractable = true;
    public string interactionText = "Click to interact";

    protected Action<TownBuilding> onClickCallback;
    protected VisualElement buildingElement;

    protected virtual void Start()
    {
        if (buildingName == "Building")
            buildingName = gameObject.name;
    }

    public virtual void SetupClickHandler(Action<TownBuilding> callback)
    {
        onClickCallback = callback;
    }

    public virtual void CreateVisualElement(VisualElement parent)
    {
        buildingElement = new VisualElement();
        buildingElement.name = $"Building_{buildingName}";
        buildingElement.AddToClassList("town-building");

        // Set position and size based on grid
        buildingElement.style.position = Position.Absolute;
        buildingElement.style.left = gridPosition.x * 50; // 50px per grid unit
        buildingElement.style.top = gridPosition.y * 50;
        buildingElement.style.width = buildingSize.x * 50;
        buildingElement.style.height = buildingSize.y * 50;
        buildingElement.style.backgroundColor = buildingColor;

        // Add click handler
        if (isInteractable)
        {
            buildingElement.RegisterCallback<ClickEvent>(OnBuildingClick);
            buildingElement.AddToClassList("town-building-interactive");
        }

        // Add building label
        var label = new Label(buildingName);
        label.AddToClassList("building-label");
        buildingElement.Add(label);

        parent.Add(buildingElement);
    }

    protected virtual void OnBuildingClick(ClickEvent evt)
    {
        if (isInteractable && onClickCallback != null)
        {
            onClickCallback.Invoke(this);
        }
    }

    public virtual void HighlightBuilding(bool highlight)
    {
        if (buildingElement != null)
        {
            if (highlight)
                buildingElement.AddToClassList("town-building-highlighted");
            else
                buildingElement.RemoveFromClassList("town-building-highlighted");
        }
    }
}
