using System.Reflection;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

public class CardBendHarnessWindow : EditorWindow
{
    private static string HandPrefabPath => HoldemPaths.Asset("DevPrefabs/Hand.prefab");
    private const string HarnessName = "Card Bend Harness [Editor Only]";
    private static readonly BindingFlags PrivateInstance = BindingFlags.Instance | BindingFlags.NonPublic;

    private HoldemGame[] tables = new HoldemGame[0];
    private int tableIndex;
    private int angleSamples = 5;
    private int heightSamples = 3;
    private float minimumAngle;
    private float maximumAngle = 60f;
    private float maximumHeight = 0.012f;
    private float horizontalSpacing = 0.22f;
    private float rowSpacing = 0.17f;

    [MenuItem("Tools/Holdem/Card Bend Harness")]
    public static void Open()
    {
        GetWindow<CardBendHarnessWindow>("Card Bend Harness");
    }

    [MenuItem("Tools/Holdem/Card Bend Harness/Build Default Array")]
    public static void BuildDefaultArray()
    {
        HoldemGame[] games = FindObjectsOfType<HoldemGame>(true);
        if (games.Length == 0)
        {
            Debug.LogError("[Card Bend Harness] No HoldemGame exists in the active scene.");
            return;
        }

        Build(games[0], 5, 3, 0f, 60f, 0.012f, 0.22f, 0.17f);
    }

    [MenuItem("Tools/Holdem/Card Bend Harness/Cleanup")]
    public static void CleanupAll()
    {
        HoldemGame[] games = FindObjectsOfType<HoldemGame>(true);
        for (int i = 0; i < games.Length; i++)
            RemoveExisting(games[i]);
    }

    private void OnEnable()
    {
        SceneView.duringSceneGui += DrawLabels;
        RefreshTables();
    }

    private void OnDisable()
    {
        SceneView.duringSceneGui -= DrawLabels;
    }

    private void OnGUI()
    {
        EditorGUILayout.LabelField("Grabbable Hand Bend Harness", EditorStyles.boldLabel);
        EditorGUILayout.HelpBox(
            "Builds an Edit Mode array from the real Hand prefab. Gameplay components are disabled and the bend solver is applied directly.",
            MessageType.Info);

        if (tables.Length == 0) RefreshTables();
        string[] tableNames = new string[tables.Length];
        for (int i = 0; i < tables.Length; i++) tableNames[i] = HierarchyPath(tables[i].transform);
        tableIndex = tableNames.Length > 0 ? EditorGUILayout.Popup("Table", tableIndex, tableNames) : 0;

        angleSamples = Mathf.Clamp(EditorGUILayout.IntField("Angle Samples", angleSamples), 2, 8);
        heightSamples = Mathf.Clamp(EditorGUILayout.IntField("Height Samples", heightSamples), 1, 5);
        minimumAngle = EditorGUILayout.FloatField("Minimum Angle", minimumAngle);
        maximumAngle = EditorGUILayout.FloatField("Maximum Angle", maximumAngle);
        maximumHeight = Mathf.Max(0f, EditorGUILayout.FloatField("Maximum Height", maximumHeight));
        horizontalSpacing = Mathf.Max(0.12f, EditorGUILayout.FloatField("Horizontal Spacing", horizontalSpacing));
        rowSpacing = Mathf.Max(0.12f, EditorGUILayout.FloatField("Row Spacing", rowSpacing));

        using (new EditorGUI.DisabledScope(CurrentTable() == null))
        {
            if (GUILayout.Button("Build / Refresh Array"))
                Build(CurrentTable(), angleSamples, heightSamples, minimumAngle, maximumAngle,
                    maximumHeight, horizontalSpacing, rowSpacing);
            if (GUILayout.Button("Cleanup"))
                RemoveExisting(CurrentTable());
        }

        if (GUILayout.Button("Refresh Tables")) RefreshTables();
    }

    private void RefreshTables()
    {
        tables = FindObjectsOfType<HoldemGame>(true);
        if (tableIndex >= tables.Length) tableIndex = 0;
    }

    private HoldemGame CurrentTable()
    {
        return tableIndex >= 0 && tableIndex < tables.Length ? tables[tableIndex] : null;
    }

    private static void Build(HoldemGame table, int angleCount, int heightCount,
        float minAngle, float maxAngle, float maxHeight, float columnSpacing, float sampleRowSpacing)
    {
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(HandPrefabPath);
        if (table == null || prefab == null)
        {
            Debug.LogError("[Card Bend Harness] Table or Hand prefab is missing.");
            return;
        }

        Undo.IncrementCurrentGroup();
        int undoGroup = Undo.GetCurrentGroup();
        Undo.SetCurrentGroupName("Build Card Bend Harness");
        RemoveExisting(table);

        GameObject root = new GameObject(HarnessName) { tag = "EditorOnly" };
        Undo.RegisterCreatedObjectUndo(root, "Build Card Bend Harness");
        root.transform.SetParent(table.transform, false);

        float surfaceY = table.potPile != null
            ? table.transform.InverseTransformPoint(table.potPile.transform.position).y + 0.025f
            : 1.1f;

        int sampleIndex = 0;
        for (int axis = 0; axis < 2; axis++)
        {
            string axisName = axis == 0 ? "X" : "Z";
            int edge = axis == 0 ? 3 : 0;
            for (int heightIndex = 0; heightIndex < heightCount; heightIndex++)
            {
                float height = heightCount > 1 ? Mathf.Lerp(0f, maxHeight, heightIndex / (float)(heightCount - 1)) : 0f;
                int row = axis * heightCount + heightIndex;
                for (int angleIndex = 0; angleIndex < angleCount; angleIndex++)
                {
                    float angle = Mathf.Lerp(minAngle, maxAngle, angleIndex / (float)(angleCount - 1));
                    Vector3 localPosition = new Vector3(
                        (angleIndex - (angleCount - 1) * 0.5f) * columnSpacing,
                        surfaceY,
                        (row - (heightCount * 2 - 1) * 0.5f) * sampleRowSpacing);

                    GameObject surfaceObject = new GameObject($"Surface {axisName} {angle:0.#} deg {height * 1000f:0.#} mm");
                    Undo.RegisterCreatedObjectUndo(surfaceObject, "Build Card Bend Harness");
                    surfaceObject.transform.SetParent(root.transform, false);
                    surfaceObject.transform.localPosition = localPosition;
                    BoxCollider surface = surfaceObject.AddComponent<BoxCollider>();
                    surface.size = new Vector3(0.2f, 0.002f, 0.2f);
                    surface.enabled = false;

                    GameObject sample = (GameObject)PrefabUtility.InstantiatePrefab(prefab, table.gameObject.scene);
                    Undo.RegisterCreatedObjectUndo(sample, "Build Card Bend Harness");
                    sample.name = $"Cards {axisName} {angle:0.#} deg {height * 1000f:0.#} mm";
                    sample.transform.SetParent(root.transform, false);
                    sample.transform.localPosition = localPosition;
                    sample.transform.localRotation = axis == 0
                        ? Quaternion.Euler(angle, 0f, 0f)
                        : Quaternion.Euler(0f, 0f, angle);

                    GrabbableHand hand = sample.GetComponent<GrabbableHand>();
                    PrepareSample(sample, hand, surface, sampleIndex++, edge, height);
                }
            }
        }

        Undo.CollapseUndoOperations(undoGroup);
        EditorSceneManager.MarkSceneDirty(table.gameObject.scene);
        Selection.activeGameObject = root;
        SceneView.lastActiveSceneView?.FrameSelected();
        SceneView.RepaintAll();
        Debug.Log($"[Card Bend Harness] Built {angleCount * heightCount * 2} X/Z samples from "
            + $"{minAngle:0.#} to {maxAngle:0.#} degrees and 0 to {maxHeight * 1000f:0.#} mm over {table.name}.");
    }

    private static void PrepareSample(GameObject sample, GrabbableHand hand, BoxCollider surface,
        int sampleIndex, int edge, float height)
    {
        foreach (Behaviour behaviour in sample.GetComponentsInChildren<Behaviour>(true))
            behaviour.enabled = false;
        foreach (Collider collider in sample.GetComponentsInChildren<Collider>(true))
            collider.enabled = false;
        foreach (Rigidbody body in sample.GetComponentsInChildren<Rigidbody>(true))
        {
            body.isKinematic = true;
            body.useGravity = false;
        }

        if (hand == null || hand.peekCard0 == null || hand.peekCard1 == null)
            return;

        hand.enableCardFolding = true;
        hand.peekSurface = surface;
        SetCard(hand.hole0, sampleIndex * 2);
        SetCard(hand.hole1, sampleIndex * 2 + 1);

        Invoke(hand, "InitializePeekRig");
        int[] contactIndices = ContactIndices(hand, edge);
        Vector3 contactCenter = Vector3.zero;
        for (int i = 0; i < contactIndices.Length; i++)
            contactCenter += hand.peekBones0[contactIndices[i]].position;
        contactCenter /= contactIndices.Length;

        Vector3 planePoint = surface.transform.TransformPoint(
            surface.center + Vector3.down * surface.size.y * 0.5f + Vector3.up * hand.peekSnapHeight);
        Vector3 normal = surface.transform.up;
        sample.transform.position += normal * Vector3.Dot(planePoint - contactCenter, normal);
        sample.transform.position += normal * height;

        Apply(hand, hand.peekCard0, hand.peekBones0, "peekRestPositions0", "peekTargets0",
            hand.peekAxisA0, hand.peekAxisB0, edge);
        Apply(hand, hand.peekCard1, hand.peekBones1, "peekRestPositions1", "peekTargets1",
            hand.peekAxisA1, hand.peekAxisB1, edge);
    }

    private static int[] ContactIndices(GrabbableHand hand, int edge)
    {
        int length = edge < 2 ? hand.peekRows : hand.peekColumns;
        int[] result = new int[length];
        for (int i = 0; i < length; i++)
        {
            if (edge == 0) result[i] = i * hand.peekColumns;
            else if (edge == 1) result[i] = i * hand.peekColumns + hand.peekColumns - 1;
            else if (edge == 2) result[i] = i;
            else result[i] = (hand.peekRows - 1) * hand.peekColumns + i;
        }
        return result;
    }

    private static void Apply(GrabbableHand hand, Transform card, Transform[] bones,
        string restField, string targetField, Vector3 axisA, Vector3 axisB, int edge)
    {
        Invoke(hand, "ApplyPeekRig", card, bones, GetField(hand, restField), GetField(hand, targetField), axisA, axisB, edge);
    }

    private static object GetField(GrabbableHand hand, string name)
    {
        return typeof(GrabbableHand).GetField(name, PrivateInstance).GetValue(hand);
    }

    private static object Invoke(GrabbableHand hand, string name, params object[] arguments)
    {
        return typeof(GrabbableHand).GetMethod(name, PrivateInstance).Invoke(hand, arguments);
    }

    private static void SetCard(PlayingCard card, int id)
    {
        if (card == null) return;
        card.id = id % 52;
        typeof(PlayingCard).GetMethod("Start", PrivateInstance).Invoke(card, null);
        card.SetVisible(true);
    }

    private static void RemoveExisting(HoldemGame table)
    {
        if (table == null) return;
        Transform existing = table.transform.Find(HarnessName);
        if (existing != null) Undo.DestroyObjectImmediate(existing.gameObject);
        EditorSceneManager.MarkSceneDirty(table.gameObject.scene);
    }

    private static void DrawLabels(SceneView sceneView)
    {
        HoldemGame[] games = FindObjectsOfType<HoldemGame>(true);
        for (int i = 0; i < games.Length; i++)
        {
            Transform root = games[i].transform.Find(HarnessName);
            if (root == null) continue;
            for (int child = 0; child < root.childCount; child++)
            {
                Transform sample = root.GetChild(child);
                if (!sample.name.StartsWith("Cards ")) continue;
                Handles.color = new Color(0.2f, 0.9f, 1f, 0.8f);
                Handles.Label(sample.position + games[i].transform.up * 0.08f, sample.name.Substring(6));
            }
        }
    }

    private static string HierarchyPath(Transform value)
    {
        string path = value.name;
        while (value.parent != null)
        {
            value = value.parent;
            path = value.name + "/" + path;
        }
        return path;
    }
}
