using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;

public class ChipTransferTuningWindow : EditorWindow
{

    private struct SweepConfig
    {
        public float spring;
        public float integral;
        public float integralLimit;
        public float damping;
        public float acceleration;
        public float transport;
        public float radius;

        public SweepConfig(float spring, float integral, float integralLimit, float damping,
            float acceleration, float transport, float radius)
        {
            this.spring = spring;
            this.integral = integral;
            this.integralLimit = integralLimit;
            this.damping = damping;
            this.acceleration = acceleration;
            this.transport = transport;
            this.radius = radius;
        }
    }

    private class ChipSample
    {
        public Rigidbody body;
        public Vector3 start;
        public Vector3 checkpoint;
        public float lastProgressTime;
        public float closestDistance = float.MaxValue;
    }

    private static readonly BindingFlags PrivateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
    private readonly List<ChipSample> samples = new List<ChipSample>();
    private readonly List<SweepConfig> sweep = new List<SweepConfig>();
    private readonly List<string> results = new List<string>();

    private HoldemGame[] tables = new HoldemGame[0];
    private int tableIndex;
    private int seatIndex = -1;
    private int chipsPerSeat = 8;
    private float spring = 24f;
    private float integral = 4f;
    private float integralLimit = 0.08f;
    private float damping = 8f;
    private float maxAcceleration = 20f;
    private float transportDuration = 0.75f;
    private float targetRadius = 0.075f;
    private float hoverHeight = 0.02f;
    private float captureRadius = 0.14f;
    private float stallSpeed = 0.03f;
    private float stallMovement = 0.004f;
    private float runStartTime;
    private float runEndTime;
    private bool running;
    private bool sweeping;
    private int sweepIndex;
    private string status = "Enter Play Mode, choose a table, then run a scenario.";

    [MenuItem("Tools/Holdem/Chip Transfer Tuning")]
    public static void Open()
    {
        GetWindow<ChipTransferTuningWindow>("Chip Transfer Tuning");
    }

    private void OnEnable()
    {
        EditorApplication.playModeStateChanged += OnPlayModeChanged;
        SceneView.duringSceneGui += DrawSceneDiagnostics;
        RefreshTables();
    }

    private void OnDisable()
    {
        EditorApplication.playModeStateChanged -= OnPlayModeChanged;
        SceneView.duringSceneGui -= DrawSceneDiagnostics;
    }

    private void OnPlayModeChanged(PlayModeStateChange change)
    {
        if (change == PlayModeStateChange.EnteredPlayMode || change == PlayModeStateChange.EnteredEditMode)
        {
            running = false;
            sweeping = false;
            RefreshTables();
            Repaint();
        }
    }

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

    private void OnGUI()
    {
        EditorGUILayout.LabelField("Real Table Physics Harness", EditorStyles.boldLabel);
        EditorGUILayout.HelpBox("Runs only in Unity Play Mode. It uses the table's real piles, pools, colliders, chips, and surface geometry.", MessageType.Info);

        if (!Application.isPlaying)
        {
            if (GUILayout.Button("Enter Play Mode")) EditorApplication.isPlaying = true;
            EditorGUILayout.LabelField(status, EditorStyles.wordWrappedLabel);
            return;
        }

        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;
        if (GUILayout.Button("Refresh Tables")) RefreshTables();

        seatIndex = EditorGUILayout.IntField("Seat (-1 = all)", seatIndex);
        chipsPerSeat = Mathf.Max(1, EditorGUILayout.IntField("Chips Per Seat", chipsPerSeat));
        spring = Mathf.Max(0f, EditorGUILayout.FloatField("PID Spring", spring));
        integral = Mathf.Max(0f, EditorGUILayout.FloatField("PID Integral", integral));
        integralLimit = Mathf.Max(0f, EditorGUILayout.FloatField("Integral Limit", integralLimit));
        damping = Mathf.Max(0f, EditorGUILayout.FloatField("PD Damping", damping));
        maxAcceleration = Mathf.Max(0f, EditorGUILayout.FloatField("Max Acceleration", maxAcceleration));
        transportDuration = Mathf.Max(0f, EditorGUILayout.FloatField("Transport Duration", transportDuration));
        targetRadius = Mathf.Max(0f, EditorGUILayout.FloatField("Target Radius", targetRadius));
        hoverHeight = Mathf.Max(0f, EditorGUILayout.FloatField("Hover Height", hoverHeight));
        captureRadius = Mathf.Max(targetRadius, EditorGUILayout.FloatField("Capture Radius", captureRadius));

        using (new EditorGUI.DisabledScope(running || tables.Length == 0))
        {
            if (GUILayout.Button("Run Scenario")) BeginRun(false);
            if (GUILayout.Button("Run Recommended Sweep")) BeginSweep();
        }
        using (new EditorGUI.DisabledScope(!running))
        {
            if (GUILayout.Button("Stop And Freeze")) FinishRun(true);
        }
        if (GUILayout.Button("Cleanup Piles")) Cleanup();

        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Status", EditorStyles.boldLabel);
        EditorGUILayout.TextArea(status, GUILayout.MinHeight(55f));
        if (results.Count > 0)
        {
            EditorGUILayout.LabelField("Results", EditorStyles.boldLabel);
            EditorGUILayout.TextArea(string.Join("\n", results.ToArray()), GUILayout.MinHeight(120f));
        }
    }

    private void Update()
    {
        if (!Application.isPlaying || !running || CurrentTable() == null) return;

        PokerChipPile pot = CurrentTable().potPile;
        float now = Time.time;
        for (int i = 0; i < samples.Count; i++)
        {
            ChipSample sample = samples[i];
            if (sample.body == null) continue;
            float distance = PlanarDistance(sample.body.worldCenterOfMass, pot.transform.position, pot.transform.up);
            if (distance < sample.closestDistance) sample.closestDistance = distance;
            if (Vector3.Distance(sample.body.position, sample.checkpoint) >= stallMovement)
            {
                sample.checkpoint = sample.body.position;
                sample.lastProgressTime = now;
            }
        }

        status = CurrentMetrics(false);
        if (now >= runEndTime) FinishRun(false);
        Repaint();
        SceneView.RepaintAll();
    }

private void BeginSweep()
    {
        sweep.Clear();
        results.Clear();
        sweep.Add(new SweepConfig(24f, 2f, 0.06f, 8f, 25f, 0.75f, 0.075f));
        sweep.Add(new SweepConfig(32f, 2f, 0.06f, 10f, 30f, 0.75f, 0.075f));
        sweep.Add(new SweepConfig(32f, 4f, 0.08f, 10f, 30f, 1.0f, 0.075f));
        sweep.Add(new SweepConfig(40f, 4f, 0.08f, 12f, 40f, 1.0f, 0.075f));
        sweep.Add(new SweepConfig(32f, 6f, 0.08f, 10f, 30f, 1.0f, 0.06f));
        sweep.Add(new SweepConfig(40f, 6f, 0.10f, 12f, 40f, 1.0f, 0.06f));
        sweepIndex = 0;
        sweeping = true;
        ApplySweepConfig();
        BeginRun(true);
    }

private void ApplySweepConfig()
    {
        SweepConfig value = sweep[sweepIndex];
        spring = value.spring;
        integral = value.integral;
        integralLimit = value.integralLimit;
        damping = value.damping;
        maxAcceleration = value.acceleration;
        transportDuration = value.transport;
        targetRadius = value.radius;
        seatIndex = -1;
    }

private void BeginRun(bool fromSweep)
    {
        RefreshTables();
        HoldemGame game = CurrentTable();
        if (game == null || game.potPile == null)
        {
            status = "No valid HoldemGame/pot pile selected.";
            sweeping = false;
            return;
        }

        Cleanup();
        PokerChipPile pot = game.potPile;
        Configure(pot);
        Backing(pot).SendCustomEvent("OpenContainer");

        for (int i = 0; i < game.players.Length; i++)
        {
            if (seatIndex >= 0 && i != seatIndex) continue;
            HoldemPlayer player = game.players[i];
            if (player == null || player.roundContributionPile == null) continue;
            PokerChipPile source = player.roundContributionPile;
            VRC.Udon.UdonBehaviour sourceBacking = Backing(source);
            sourceBacking.SetProgramVariable("harnessTotalValue", chipsPerSeat * 5);
            sourceBacking.SendCustomEvent("_HarnessSetTotalChips");
            sourceBacking.SetProgramVariable("harnessDestination", Backing(pot));
            sourceBacking.SendCustomEvent("_HarnessTransferAllAnimated");
        }

        CaptureSamples(pot);
        if (samples.Count == 0)
        {
            status = "No chips moved. Check seat selection and pool availability.";
            sweeping = false;
            return;
        }

        Backing(pot).SendCustomEvent("StartAnimatedGather");
        runStartTime = Time.time;
        runEndTime = runStartTime + transportDuration + pot.gatherSettleDuration + 0.1f;
        running = true;
        status = "Running PID gather with " + samples.Count + " chips.";
    }

private void Configure(PokerChipPile pot)
    {
        VRC.Udon.UdonBehaviour backing = Backing(pot);
        backing.SetProgramVariable("enableGatherPd", true);
        backing.SetProgramVariable("gatherPdSpring", spring);
        backing.SetProgramVariable("gatherPidIntegral", integral);
        backing.SetProgramVariable("gatherPidIntegralLimit", integralLimit);
        backing.SetProgramVariable("gatherPdDamping", damping);
        backing.SetProgramVariable("gatherPdMaxAcceleration", maxAcceleration);
        backing.SetProgramVariable("gatherTransportDuration", transportDuration);
        backing.SetProgramVariable("gatherPdTargetRadius", targetRadius);
        backing.SetProgramVariable("gatherPdHoverHeight", hoverHeight);
        backing.SetProgramVariable("preservePhysicsPlacement", true);
    }

private void CaptureSamples(PokerChipPile pot)
    {
        samples.Clear();
        Rigidbody[] bodies = pot.GetComponentsInChildren<Rigidbody>(true);
        for (int i = 0; i < bodies.Length; i++)
        {
            Rigidbody body = bodies[i];
            if (body == null || body.gameObject == pot.gameObject || !body.gameObject.activeInHierarchy
                || body.transform.parent != pot.transform) continue;
            samples.Add(new ChipSample
            {
                body = body,
                start = body.position,
                checkpoint = body.position,
                lastProgressTime = Time.time
            });
        }
    }

private void FinishRun(bool interrupted)
    {
        if (!running) return;
        string summary = CurrentMetrics(true);
        results.Add((interrupted ? "INTERRUPTED " : "")
            + "K=" + spring + " I=" + integral + " IL=" + integralLimit
            + " D=" + damping + " A=" + maxAcceleration + " T=" + transportDuration + " R=" + targetRadius
            + " | " + summary.Replace("\n", "; "));

        HoldemGame game = CurrentTable();
        if (game != null && game.potPile != null) Backing(game.potPile).SendCustomEvent("FinishAnimatedGather");
        running = false;

        if (sweeping && !interrupted)
        {
            sweepIndex++;
            if (sweepIndex < sweep.Count)
            {
                ApplySweepConfig();
                BeginRun(true);
                return;
            }
            sweeping = false;
            status = "Sweep complete.\n" + summary;
        }
        else
        {
            sweeping = false;
            status = summary;
        }
    }

    private string CurrentMetrics(bool final)
    {
        HoldemGame game = CurrentTable();
        if (game == null || game.potPile == null) return "Table unavailable.";
        PokerChipPile pot = game.potPile;
        int arrived = 0;
        int stalled = 0;
        int escaped = 0;
        float maxDistance = 0f;
        float now = Time.time;

        for (int i = 0; i < samples.Count; i++)
        {
            ChipSample sample = samples[i];
            if (sample.body == null) continue;
            float distance = PlanarDistance(sample.body.worldCenterOfMass, pot.transform.position, pot.transform.up);
            if (distance <= captureRadius) arrived++;
            if (distance > maxDistance) maxDistance = distance;
            float movedRecently = Vector3.Distance(sample.body.position, sample.checkpoint);
            if (distance > captureRadius && now - sample.lastProgressTime >= 0.3f
                && sample.body.velocity.magnitude < stallSpeed && movedRecently < stallMovement)
                stalled++;
            float vertical = Vector3.Dot(sample.body.worldCenterOfMass - pot.transform.position, pot.transform.up);
            if (vertical < -0.1f || distance > 2f) escaped++;
        }

        float elapsed = Mathf.Max(0f, now - runStartTime);
        return (final ? "FINAL " : "") + "elapsed=" + elapsed.ToString("F2") + "s"
            + " arrived=" + arrived + "/" + samples.Count
            + " stalled=" + stalled
            + " escaped=" + escaped
            + " maxDistance=" + maxDistance.ToString("F3") + "m";
    }

private void Cleanup()
    {
        HoldemGame game = CurrentTable();
        if (game == null) return;
        running = false;
        if (game.potPile != null)
        {
            Backing(game.potPile).SendCustomEvent("FinishAnimatedGather");
            Backing(game.potPile).SendCustomEvent("ReleaseAllToPools");
        }
        if (game.players != null)
        {
            for (int i = 0; i < game.players.Length; i++)
            {
                HoldemPlayer player = game.players[i];
                if (player == null || player.roundContributionPile == null) continue;
                Backing(player.roundContributionPile).SendCustomEvent("FinishAnimatedGather");
                Backing(player.roundContributionPile).SendCustomEvent("ReleaseAllToPools");
            }
        }
        samples.Clear();
        status = "Piles cleaned up.";
    }

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

    private void DrawSceneDiagnostics(SceneView sceneView)
    {
        if (!running || CurrentTable() == null || CurrentTable().potPile == null) return;
        PokerChipPile pot = CurrentTable().potPile;
        Handles.color = Color.cyan;
        Handles.DrawWireDisc(pot.transform.position, pot.transform.up, captureRadius);
        for (int i = 0; i < samples.Count; i++)
        {
            ChipSample sample = samples[i];
            if (sample.body == null) continue;
            float distance = PlanarDistance(sample.body.worldCenterOfMass, pot.transform.position, pot.transform.up);
            Handles.color = distance <= captureRadius ? Color.green : Color.red;
            Handles.DrawLine(sample.body.worldCenterOfMass, pot.transform.position);
            Handles.SphereHandleCap(0, sample.body.worldCenterOfMass, Quaternion.identity, 0.012f, EventType.Repaint);
        }
    }

    private static float PlanarDistance(Vector3 a, Vector3 b, Vector3 up)
    {
        Vector3 delta = a - b;
        delta -= up * Vector3.Dot(delta, up);
        return delta.magnitude;
    }

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


private static VRC.Udon.UdonBehaviour Backing(PokerChipPile pile)
    {
        return pile != null ? pile.GetComponent<VRC.Udon.UdonBehaviour>() : null;
    }
}
