using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class DraggableKey : MonoBehaviour,
    IBeginDragHandler, IDragHandler, IEndDragHandler, ITask
{
    [Header("Key Settings")]
    public string keyID;
    public string correctSlotID;
    public string previousSceneName;


    [Header("Visual")]
    public Color wrongAttemptColor = Color.red;
    public float blinkDuration = 0.2f;

    private RectTransform rectTransform;
    private CanvasGroup canvasGroup;
    private Vector2 startPosition;

    private bool isOverCorrectSlot = false;


    public string TaskID { get; set; }
    public TaskType TaskType { get; set; }
    public string TaskName { get; set; }
    public (double, double) TaskLocation { get; set; }
    public bool IsCompleted { get; private set; }

    private Action<ITask> _onCompleted;
    private Action<ITask> _onExit;

    public void Initialize(Action<ITask> onCompleted)
    {
        IsCompleted = false;
        _onCompleted = onCompleted;
        // Register ourselves with the manager so CheckWin can call Complete()
        if (KeyminigameManager.Instance != null)
            KeyminigameManager.Instance.taskRef = this;
    }

    public void Complete()
    {
        if (IsCompleted) return;

        IsCompleted = true;
        _onCompleted?.Invoke(this);
        ExitTask(_onExit);
    }

    public void ExitTask(Action<ITask> onExit)
    {
        onExit?.Invoke(this);
    }

    // ===== UNITY =====

    private void Awake()
    {
        rectTransform = GetComponent<RectTransform>();
        canvasGroup = GetComponent<CanvasGroup>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        startPosition = rectTransform.anchoredPosition;
        canvasGroup.blocksRaycasts = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        rectTransform.anchoredPosition += eventData.delta;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        canvasGroup.blocksRaycasts = true;

        if (isOverCorrectSlot)
        {
            Complete();
        }

    }



    public void SetSlotMatch(bool value)
    {
        isOverCorrectSlot = value;
    }


    void ResetPosition()
    {
        rectTransform.anchoredPosition = startPosition;
    }
}