using AceFieldNewHorizon.Scripts.System;
using Godot;

namespace AceFieldNewHorizon.Scripts.Tiles;

public partial class MinerTile : BaseTile
{
    [Export] public PackedScene ItemPickup { get; set; }
    [Export] public string ItemToMine { get; set; }
    [Export] public int MiningRate = 1; // Items per second

    private Vector2I _gridPosition;
    private float _timeSinceLastMine;

    public override void _Ready()
    {
        base._Ready();
        _gridPosition = GridUtils.WorldToGrid(Position);

        var ground = Grid.GetTileAtCell(_gridPosition, GridLayer.Ground) as BaseTile;
        if (ground == null)
        {
            GD.Print($"[Miner] Miner {GetInstanceId()} not found available resource...");
            return;
        }

        ItemToMine = (ground.TileId) switch
        {
            "stone" => "stone",
            "ore_iron" => "ore_iron",
            _ => null
        };
        if (ItemToMine == null)
            GD.Print($"[Miner] Miner {GetInstanceId()} not found available resource...");
    }

    public override void _Process(double delta)
    {
        if (ItemToMine == null)
            return;
        
        // Don't mine if building is not completed
        if (!IsConstructed || ItemPickup == null)
            return;

        _timeSinceLastMine += (float)delta;

        if (!(_timeSinceLastMine >= 1f / MiningRate)) return;
        _timeSinceLastMine = 0f;
        SpawnItem();
    }

    private void SpawnItem()
    {
        var itemPickup = ItemPickup?.Instantiate<ItemPickup>();
        if (itemPickup == null) return;

        itemPickup.ItemId = ItemToMine;
        itemPickup.Quantity = 1;

        // Initial position (slightly below the spawn point)
        const int halfTileSize = GridUtils.TileSize / 2;
        var spawnPosition = GridUtils.GridToWorld(_gridPosition);
        var targetY = spawnPosition.Y - halfTileSize; // Target Y position
        var targetX = spawnPosition.X + halfTileSize + (GD.Randf() * 10f - 5f);
        itemPickup.Position =
            new Vector2(spawnPosition.X + halfTileSize, spawnPosition.Y + 16); // Start below
        itemPickup.Scale = Vector2.Zero; // Start invisible

        // Add to the scene
        GetTree().CurrentScene.AddChild(itemPickup);

        // Create the pop-up animation
        var tween = CreateTween().SetTrans(Tween.TransitionType.Elastic).SetEase(Tween.EaseType.Out);

        // Animate the pop-up effect
        tween.TweenProperty(itemPickup, "position:y", targetY, 0.6f);
        tween.Parallel().TweenProperty(itemPickup, "scale", Vector2.One, 0.6f);

        // Optional: Add a slight horizontal wobble
        tween.Parallel().TweenProperty(itemPickup, "position:x", targetX, 0.6f);
    }
}