using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using VRC.SDKBase;

public class PhysicalRaiseSelectionHarnessWindow : EditorWindow
{
    private const string RootName = "Physical Raise Selection Harness [Editor Only]";

    private readonly List<Transform> chipMarkers = new List<Transform>();
    private PhysicalRaisePile[] controllers = new PhysicalRaisePile[0];
    private int controllerIndex;
    private int denominationIndex;
    private int columnIndex;
    private int referenceTotalChips = 10;
    private bool useTrackedHand = true;
    private bool leftHand = true;
    private Vector3 readoutPosition;
    private Quaternion handRotation = Quaternion.identity;
    private Vector3 simulatedHandPosition;

    private GameObject root;
    private Transform rawHandMarker;
    private Transform checkedPositionMarker;
    private Transform shoulderMarker;
    private Transform readoutMarker;
    private Transform armBone;
    private Material rawHandMaterial;
    private Material checkedMaterial;
    private Material readoutMaterial;
    private Material armMaterial;
    private Material chipMaterial;
    private Material selectedChipMaterial;

    private Vector3 rawHandPosition;
    private Vector3 checkedPosition;
    private Vector3 shoulderPosition;
    private Vector3 armDirection;
    private Vector3 columnBase;
    private float columnTopY;
    private float chipWorldHeight;
    private float depth;
    private int columnChips;
    private int selectedChips;
    private int maxPerClick;
    private bool insideRadius;
    private bool insideHeight;
    private string status = "Enter Play Mode to inspect tracked hand selection.";

    [MenuItem("Tools/Holdem/Physical Raise Selection Harness")]
    public static void Open()
    {
        GetWindow<PhysicalRaiseSelectionHarnessWindow>("Raise Selection Harness");
    }

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

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

    private void OnPlayModeChanged(PlayModeStateChange change)
    {
        CleanupVisuals();
        RefreshControllers();
        Repaint();
    }

    private void OnGUI()
    {
        EditorGUILayout.LabelField("Physical Raise Hand Selection", EditorStyles.boldLabel);
        EditorGUILayout.HelpBox(
            "Red = tracked hand origin. Cyan = the hand point after Hand Offset (selection + readout). "
            + "Magenta = the same end position in the arm-aligned frame. "
            + "Yellow = illustrative virtual shoulder-to-hand arm bone. The reference tower uses the production selection math.",
            MessageType.Info);

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

        if (controllers.Length == 0) RefreshControllers();
        string[] names = new string[controllers.Length];
        for (int i = 0; i < controllers.Length; i++)
            names[i] = controllers[i] == null ? "Missing" : HierarchyPath(controllers[i].transform);
        controllerIndex = names.Length == 0 ? 0 : EditorGUILayout.Popup("Raise Controller", controllerIndex, names);
        if (GUILayout.Button("Refresh Controllers")) RefreshControllers();

        PhysicalRaisePile controller = CurrentController();
        int denominationCount = controller != null && controller.sourcePile != null
            && controller.sourcePile.denominationValues != null ? controller.sourcePile.denominationValues.Length : 0;
        denominationIndex = Mathf.Clamp(EditorGUILayout.IntField("Denomination Index", denominationIndex),
            0, Mathf.Max(0, denominationCount - 1));
        referenceTotalChips = Mathf.Max(1, EditorGUILayout.IntField("Reference Chips", referenceTotalChips));
        int stackHeight = controller != null && controller.sourcePile != null
            ? Mathf.Max(1, controller.sourcePile.stackHeight) : 10;
        int columns = Mathf.Max(1, Mathf.CeilToInt(referenceTotalChips / (float)stackHeight));
        columnIndex = Mathf.Clamp(EditorGUILayout.IntField("Selected Column", columnIndex), 0, columns - 1);
        useTrackedHand = EditorGUILayout.Toggle("Use Tracked Hand", useTrackedHand);
        leftHand = EditorGUILayout.Toggle("Left Hand", leftHand);
        if (controller != null)
            controller.handOffset = EditorGUILayout.Vector3Field("Hand Offset", controller.handOffset);
        if (!useTrackedHand) simulatedHandPosition = EditorGUILayout.Vector3Field("Simulated Hand", simulatedHandPosition);
        if (GUILayout.Button("Place Simulated Hand At Tower Top") && controller != null)
        {
            UpdateReferenceGeometry(controller);
            simulatedHandPosition = new Vector3(columnBase.x,
                columnTopY - controller.handOffset.y, columnBase.z);
            useTrackedHand = false;
        }

        EditorGUILayout.Space();
        EditorGUILayout.LabelField("Live Values", EditorStyles.boldLabel);
        EditorGUILayout.LabelField("Tracked hand", Format(rawHandPosition));
        EditorGUILayout.LabelField("Checked position", Format(checkedPosition));
        EditorGUILayout.LabelField("Readout position", Format(readoutPosition));
        EditorGUILayout.LabelField("Arm direction", Format(armDirection));
        EditorGUILayout.LabelField("Column base", Format(columnBase));
        EditorGUILayout.LabelField("Column top Y", columnTopY.ToString("F4") + " m");
        EditorGUILayout.LabelField("Chip world height", chipWorldHeight.ToString("F4") + " m");
        EditorGUILayout.LabelField("Depth", depth.ToString("F3") + " chips");
        EditorGUILayout.LabelField("Column chips", columnChips.ToString());
        EditorGUILayout.LabelField("Max per click", maxPerClick.ToString());
        EditorGUILayout.LabelField("Selected chips", selectedChips.ToString());
        EditorGUILayout.LabelField("Inside radius", insideRadius.ToString());
        EditorGUILayout.LabelField("Inside height", insideHeight.ToString());
        EditorGUILayout.HelpBox(status, selectedChips > 0 ? MessageType.Info : MessageType.Warning);
    }

    private void Update()
    {
        if (!Application.isPlaying) return;
        PhysicalRaisePile controller = CurrentController();
        if (controller == null || controller.sourcePile == null)
        {
            status = "No PhysicalRaisePile with a source pile is available.";
            Repaint();
            return;
        }

        EnsureVisuals();
        UpdateReferenceGeometry(controller);
        if (!TryGetHand(controller, out rawHandPosition, out shoulderPosition, out handRotation))
        {
            status = "No local VRChat player tracking data. Disable Use Tracked Hand to use the simulated position.";
            SetVisualsActive(false);
            Repaint();
            return;
        }

        checkedPosition = PhysicalRaiseSelectionMath.HandPoint(
            rawHandPosition, handRotation, controller.handOffset);
        Vector3 arm = rawHandPosition - shoulderPosition;
        readoutPosition = PhysicalRaiseSelectionMath.HandPoint(
            rawHandPosition, handRotation, controller.handOffset);
        armDirection = arm.sqrMagnitude > 0.000001f ? arm.normalized : Vector3.forward;
        float dx = checkedPosition.x - columnBase.x;
        float dz = checkedPosition.z - columnBase.z;
        insideRadius = dx * dx + dz * dz <= controller.selectionRadius * controller.selectionRadius;
        float baseY = columnBase.y;
        insideHeight = checkedPosition.y >= baseY - controller.selectionHeightBelowStack
            && checkedPosition.y <= columnTopY + controller.selectionHeightAboveStack;
        depth = chipWorldHeight > 0f ? (columnTopY - checkedPosition.y) / chipWorldHeight : 0f;
        int heightSelection = PhysicalRaiseSelectionMath.SelectionCount(columnTopY, checkedPosition.y,
            chipWorldHeight, columnChips, controller.sourcePile.stackHeight);
        selectedChips = insideRadius && insideHeight ? heightSelection : 0;

        UpdateMarkers();
        UpdateChipMarkers(controller);
        status = referenceTotalChips + " chips => " + ReferenceBreakdown(referenceTotalChips,
            controller.sourcePile.stackHeight) + ". Column " + columnIndex + " allows at most "
            + maxPerClick + " chips; current hand selects " + selectedChips + ".";
        Repaint();
        SceneView.RepaintAll();
    }

    private void UpdateReferenceGeometry(PhysicalRaisePile controller)
    {
        PokerChipPile source = controller.sourcePile;
        int stackHeight = Mathf.Max(1, source.stackHeight);
        columnChips = PhysicalRaiseSelectionMath.ChipsInColumn(referenceTotalChips, columnIndex, stackHeight);
        maxPerClick = Mathf.Min(columnChips, stackHeight);
        columnBase = source.GetDenominationColumnWorldPosition(denominationIndex, columnIndex);
        chipWorldHeight = source.chipHeight * Mathf.Abs(source.transform.lossyScale.y);
        columnTopY = columnBase.y + columnChips * chipWorldHeight;
    }

private bool TryGetHand(PhysicalRaisePile controller, out Vector3 hand, out Vector3 shoulder, out Quaternion rotation)
    {
        if (!useTrackedHand)
        {
            hand = simulatedHandPosition;
            shoulder = hand + new Vector3(leftHand ? 0.25f : -0.25f, 0.18f, -0.12f);
            Vector3 simulatedArm = hand - shoulder;
            rotation = simulatedArm.sqrMagnitude > 0.000001f
                ? Quaternion.LookRotation(simulatedArm.normalized, Vector3.up)
                : Quaternion.identity;
            return true;
        }

        VRCPlayerApi local = Networking.LocalPlayer;
        if (local == null)
        {
            hand = Vector3.zero;
            shoulder = Vector3.zero;
            rotation = Quaternion.identity;
            return false;
        }

        VRCPlayerApi.TrackingDataType handType = leftHand
            ? VRCPlayerApi.TrackingDataType.LeftHand : VRCPlayerApi.TrackingDataType.RightHand;
        VRCPlayerApi.TrackingData handData = local.GetTrackingData(handType);
        VRCPlayerApi.TrackingData head = local.GetTrackingData(VRCPlayerApi.TrackingDataType.Head);
        hand = handData.position;
        rotation = handData.rotation;
        Vector3 localShoulder = new Vector3(leftHand ? -0.18f : 0.18f, -0.18f, 0f);
        shoulder = head.position + head.rotation * localShoulder;
        return true;
    }

private void EnsureVisuals()
    {
        if (root != null) return;
        root = new GameObject(RootName) { hideFlags = HideFlags.DontSave };
        rawHandMaterial = CreateMaterial(new Color(1f, 0.15f, 0.1f));
        checkedMaterial = CreateMaterial(new Color(0f, 0.9f, 1f));
        armMaterial = CreateMaterial(new Color(1f, 0.75f, 0.05f));
        readoutMaterial = CreateMaterial(new Color(1f, 0.4f, 0.9f));
        chipMaterial = CreateMaterial(new Color(0.35f, 0.4f, 0.5f));
        selectedChipMaterial = CreateMaterial(new Color(0.15f, 1f, 0.3f));
        rawHandMarker = CreatePrimitive("Tracked Hand", PrimitiveType.Sphere, rawHandMaterial).transform;
        checkedPositionMarker = CreatePrimitive("Checked Position", PrimitiveType.Sphere, checkedMaterial).transform;
        readoutMarker = CreatePrimitive("Readout Position", PrimitiveType.Sphere, readoutMaterial).transform;
        shoulderMarker = CreatePrimitive("Virtual Shoulder", PrimitiveType.Sphere, armMaterial).transform;
        armBone = CreatePrimitive("Virtual Arm Bone", PrimitiveType.Cylinder, armMaterial).transform;
    }

    private GameObject CreatePrimitive(string name, PrimitiveType type, Material material)
    {
        GameObject value = GameObject.CreatePrimitive(type);
        value.name = name;
        value.hideFlags = HideFlags.DontSave;
        value.transform.SetParent(root.transform);
        Collider collider = value.GetComponent<Collider>();
        if (collider != null) DestroyImmediate(collider);
        Renderer renderer = value.GetComponent<Renderer>();
        if (renderer != null) renderer.sharedMaterial = material;
        return value;
    }

private void UpdateMarkers()
    {
        SetVisualsActive(true);
        rawHandMarker.position = rawHandPosition;
        rawHandMarker.localScale = Vector3.one * 0.025f;
        checkedPositionMarker.position = checkedPosition;
        checkedPositionMarker.localScale = Vector3.one * 0.025f;
        readoutMarker.position = readoutPosition;
        readoutMarker.localScale = Vector3.one * 0.03f;
        shoulderMarker.position = shoulderPosition;
        shoulderMarker.localScale = Vector3.one * 0.018f;

        Vector3 delta = rawHandPosition - shoulderPosition;
        armBone.position = (rawHandPosition + shoulderPosition) * 0.5f;
        armBone.up = delta.sqrMagnitude > 0.000001f ? delta.normalized : Vector3.up;
        armBone.localScale = new Vector3(0.008f, delta.magnitude * 0.5f, 0.008f);
    }

    private void UpdateChipMarkers(PhysicalRaisePile controller)
    {
        while (chipMarkers.Count < referenceTotalChips)
            chipMarkers.Add(CreatePrimitive("Reference Chip", PrimitiveType.Cylinder, chipMaterial).transform);
        for (int i = 0; i < chipMarkers.Count; i++)
        {
            Transform chip = chipMarkers[i];
            bool active = i < referenceTotalChips;
            chip.gameObject.SetActive(active);
            if (!active) continue;
            int stackHeight = Mathf.Max(1, controller.sourcePile.stackHeight);
            int column = i / stackHeight;
            int row = i % stackHeight;
            int chipsInThisColumn = PhysicalRaiseSelectionMath.ChipsInColumn(referenceTotalChips, column, stackHeight);
            Vector3 basePosition = controller.sourcePile.GetDenominationColumnWorldPosition(denominationIndex, column);
            chip.position = basePosition + Vector3.up * chipWorldHeight * (row + 0.5f);
            chip.rotation = controller.sourcePile.transform.rotation;
            chip.localScale = new Vector3(0.015f, chipWorldHeight * 0.5f, 0.015f);
            Renderer renderer = chip.GetComponent<Renderer>();
            bool selected = column == columnIndex && row >= chipsInThisColumn - selectedChips;
            if (renderer != null) renderer.sharedMaterial = selected ? selectedChipMaterial : chipMaterial;
        }
    }

    private void SetVisualsActive(bool active)
    {
        if (root != null) root.SetActive(active);
    }

    private void DrawSceneDiagnostics(SceneView sceneView)
    {
        if (!Application.isPlaying || root == null || !root.activeSelf) return;
        Handles.color = Color.red;
        Handles.Label(rawHandPosition + Vector3.up * 0.025f, "Tracked " + Format(rawHandPosition));
        Handles.color = Color.cyan;
        Handles.DrawLine(rawHandPosition, checkedPosition);
        Handles.Label(checkedPosition + Vector3.up * 0.025f,
            "Checked " + Format(checkedPosition) + "\nDepth " + depth.ToString("F2") + " => " + selectedChips);
        Handles.color = new Color(1f, 0.4f, 0.9f);
        Handles.DrawLine(rawHandPosition, readoutPosition);
        Handles.Label(readoutPosition + Vector3.up * 0.025f, "Readout " + Format(readoutPosition));
        Handles.color = Color.yellow;
        Handles.ArrowHandleCap(0, shoulderPosition, Quaternion.LookRotation(armDirection), 0.12f, EventType.Repaint);
        Handles.Label(shoulderPosition, "Virtual shoulder\nArm " + Format(armDirection));
        Handles.color = insideRadius && insideHeight ? Color.green : Color.red;
        Handles.DrawWireDisc(new Vector3(columnBase.x, columnTopY, columnBase.z), Vector3.up,
            CurrentController() != null ? CurrentController().selectionRadius : 0.06f);
    }

    private void RefreshControllers()
    {
        controllers = FindObjectsOfType<PhysicalRaisePile>(true);
        if (controllerIndex >= controllers.Length) controllerIndex = 0;
    }

    private PhysicalRaisePile CurrentController()
    {
        if (controllers == null || controllerIndex < 0 || controllerIndex >= controllers.Length) return null;
        return controllers[controllerIndex];
    }

    private void CleanupVisuals()
    {
        if (root != null) DestroyImmediate(root);
        if (rawHandMaterial != null) DestroyImmediate(rawHandMaterial);
        if (checkedMaterial != null) DestroyImmediate(checkedMaterial);
        if (readoutMaterial != null) DestroyImmediate(readoutMaterial);
        if (armMaterial != null) DestroyImmediate(armMaterial);
        if (chipMaterial != null) DestroyImmediate(chipMaterial);
        if (selectedChipMaterial != null) DestroyImmediate(selectedChipMaterial);
        root = null;
        chipMarkers.Clear();
    }

    private static Material CreateMaterial(Color color)
    {
        Shader shader = Shader.Find("Standard");
        Material material = new Material(shader) { hideFlags = HideFlags.DontSave, color = color };
        return material;
    }

    private static string ReferenceBreakdown(int total, int stackHeight)
    {
        int columns = Mathf.Max(1, Mathf.CeilToInt(total / (float)Mathf.Max(1, stackHeight)));
        string result = "";
        for (int i = 0; i < columns; i++)
        {
            if (i > 0) result += " + ";
            result += PhysicalRaiseSelectionMath.ChipsInColumn(total, i, stackHeight);
        }
        return result;
    }

    private static string Format(Vector3 value)
    {
        return "(" + value.x.ToString("F4") + ", " + value.y.ToString("F4") + ", "
            + value.z.ToString("F4") + ")";
    }

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