using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class BoxController : MonoBehaviour
{
    [Header("Fall Detection")]
    [Tooltip("If box falls below this Y value, it will reset to spawn position")]
    public float fallThresholdY = -20f;

    private SpriteRenderer pickedUpBy;
    private SpriteRenderer lastDroppedBy;  // Track who just dropped the box
    private List<SpriteRenderer> touching = new();
    
    private Vector3 spawnPosition;  // Initial position to reset to
    private Rigidbody2D rb;

    void Start()
    {
        GameManager.instance.AttachBoxController(this);
        spawnPosition = transform.position;
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (this.pickedUpBy != null)
        {
            this.transform.position = new Vector3(
                this.pickedUpBy.transform.position.x,
                this.pickedUpBy.transform.position.y + 0.5f,
                this.transform.position.z
            );
        }

        // Check if box fell out of world
        if (transform.position.y < fallThresholdY)
        {
            ResetBox();
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        SpriteRenderer sprite = collision.transform.GetComponent<SpriteRenderer>();
        if (sprite == null) return;

        if (!this.touching.Contains(sprite))
        {
            this.touching.Add(sprite);
        }
        else return;

        // If this is the player who just dropped the box, don't pick it up again
        if (sprite == this.lastDroppedBy)
        {
            return;
        }

        PlayerController player = sprite.GetComponent<PlayerController>();
        if (player == null) return;
        if (!player.canPickupBox) return;
        if (!player.IsActive()) return;

        this.pickedUpBy = sprite;
        this.lastDroppedBy = null;  // Clear since someone else picked it up
        this.GetComponent<Collider2D>().enabled = false;
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        SpriteRenderer sprite = collision.transform.GetComponent<SpriteRenderer>();
        if (sprite == null) return;

        this.touching.Remove(sprite);

        // Clear lastDroppedBy when that player exits collision
        if (sprite == this.lastDroppedBy)
        {
            this.lastDroppedBy = null;
        }
    }

    public void PutDownBox()
    {
        if (this.pickedUpBy == null) return;  // Already not picked up
        
        this.lastDroppedBy = this.pickedUpBy;  // Remember who dropped it
        this.pickedUpBy = null;
        this.touching.Clear();  // Clear touching list so new collisions are detected fresh
        this.GetComponent<Collider2D>().enabled = true;
    }

    public void ResetBox()
    {
        Debug.Log("Box fell out of world, resetting to spawn position");
        
        // Show message to player
        MessageBoxController.Show("Ooops, vrátil jsem ti ten box hezky zpátky kde byl. Zkus to znovu :)", 4f);
        
        // Reset position
        transform.position = spawnPosition;
        
        // Reset velocity if has rigidbody
        if (rb != null)
        {
            rb.linearVelocity = Vector2.zero;
            rb.angularVelocity = 0f;
        }
        
        // Reset state
        this.pickedUpBy = null;
        this.lastDroppedBy = null;
        this.touching.Clear();
        this.GetComponent<Collider2D>().enabled = true;
    }
}

