using UnityEngine;
using HeneGames.Airplane;

[DisallowMultipleComponent]
[DefaultExecutionOrder(-100)]
public class RingCheckpoint : MonoBehaviour
{
    [SerializeField] private RingCourseTracker tracker;
    [SerializeField] private int orderIndex;

    private bool passed;

    public int OrderIndex => orderIndex;
    public bool Passed => passed;

    public void Configure(RingCourseTracker courseTracker, int index)
    {
        tracker = courseTracker;
        orderIndex = index;
    }

    private void Awake()
    {
        EnsureTriggerCollider();
    }

    private void OnValidate()
    {
        if (!Application.isPlaying)
            EnsureTriggerCollider();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (passed || tracker == null)
            return;

        if (!IsAirplaneCollider(other))
            return;

        tracker.RegisterRingPass(this);
    }

    private static bool IsAirplaneCollider(Collider other)
    {
        if (other.TryGetComponent<SimpleAirPlaneCollider>(out _))
            return true;

        return other.GetComponentInParent<SimpleAirPlaneController>() != null;
    }

    private void EnsureTriggerCollider()
    {
        foreach (var meshCollider in GetComponents<MeshCollider>())
            meshCollider.enabled = false;

        if (!TryGetComponent<BoxCollider>(out var box))
            box = gameObject.AddComponent<BoxCollider>();

        box.isTrigger = true;

        if (TryGetComponent<Renderer>(out var renderer))
        {
            Bounds bounds = renderer.bounds;
            box.center = transform.InverseTransformPoint(bounds.center);
            Vector3 scale = transform.lossyScale;
            box.size = new Vector3(
                bounds.size.x / Mathf.Max(Mathf.Abs(scale.x), 0.001f),
                bounds.size.y / Mathf.Max(Mathf.Abs(scale.y), 0.001f),
                bounds.size.z / Mathf.Max(Mathf.Abs(scale.z), 0.001f));
        }
        else
        {
            box.center = Vector3.zero;
            box.size = Vector3.one * 12f;
        }
    }

    public void MarkPassed()
    {
        passed = true;

        if (TryGetComponent<Collider>(out var collider))
            collider.enabled = false;
    }

    public void ResetCheckpoint()
    {
        passed = false;
        EnsureTriggerCollider();
    }
}
