using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.SDK3.Persistence;
using TMPro;

/// <summary>
/// Calibration menu for the physical raise pile. The player rests either hand on the top chip of a
/// 10-chip pile and presses the matching button with the other hand; the arm-frame offset that puts the hand's sample point on that chip is
/// saved per player and pushed to every PhysicalRaisePile. Offsets are stored for a 0.8m eye height and scaled
/// by avatar size where they are used, always in left-hand space: a right-hand calibration is mirrored on the way in.
/// </summary>
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class HandCalibration : UdonSharpBehaviour
{
    public const string PersistenceHandOffsetKey = "S1_HoldemHandOffsetV1";

    public PokerChipPile calibrationPile;
    public PhysicalRaisePile[] piles;
    public TMP_Text label;
    public int calibrationChips = 10;
    [Tooltip("Reject the press when the tracked hand is farther than this from the top chip.")]
    public float maxHandDistance = 0.4f;

    private Vector3 currentOffset;
    private bool hasOffset;
    private string status = "";

    void Start()
    {
        if (!hasOffset) currentOffset = DefaultOffset();
        RefreshLabel();
        // The pile allocates its buffers in its own Start, which may run after this one.
        SendCustomEventDelayedFrames(nameof(_InitialFill), 2);
    }

    public void _InitialFill()
    {
        FillPile();
        if (calibrationPile != null) calibrationPile.SetTextVisibility(false);
    }

    public override void OnPlayerRestored(VRCPlayerApi player)
    {
        if (player == null || !player.isLocal) return;
        if (!PlayerData.HasKey(player, PersistenceHandOffsetKey)) return;
        Vector3 saved = PlayerData.GetVector3(player, PersistenceHandOffsetKey);
        if (!PhysicalRaiseSelectionMath.IsPlausibleOffset(saved)) return;
        currentOffset = saved;
        hasOffset = true;
        ApplyToPiles(saved);
        RefreshLabel();
    }

    /// <summary>
    /// VRCButton event: forget the saved calibration and go back to the authored default. PlayerData has no
    /// delete, so an out-of-range marker is stored instead; loading ignores anything implausible.
    /// </summary>
    public void _ResetToDefault()
    {
        VRCPlayerApi local = Networking.LocalPlayer;
        if (local == null) return;
        PlayerData.SetVector3(PersistenceHandOffsetKey, ResetMarker());
        hasOffset = false;
        ClearPiles();
        currentOffset = DefaultOffset();
        status = "Reset to default.";
        RefreshLabel();
    }

    private Vector3 ResetMarker()
    {
        return new Vector3(99f, 99f, 99f);
    }

    /// <summary>
    /// VRCButton event. Underscore-prefixed so it can never be triggered over the network: it rewrites the
    /// local player's saved calibration.
    /// </summary>
    public void _Calibrate()
    {
        CalibrateWithHand(false);
    }

    /// <summary>VRCButton event: same as _Calibrate, measured with the right hand.</summary>
    public void _CalibrateRight()
    {
        CalibrateWithHand(true);
    }

    private void CalibrateWithHand(bool rightHand)
    {
        VRCPlayerApi local = Networking.LocalPlayer;
        if (local == null || calibrationPile == null) return;
        if (!local.IsUserInVR())
        {
            Say("Calibration needs VR");
            return;
        }

        FillPile();
        if (calibrationPile.GetDenominationColumnChipCount(0, 0) < calibrationChips)
        {
            Say("Calibration pile unavailable");
            return;
        }

        // Aim at the middle of the top chip: that is where SelectionCount counts exactly one chip.
        Vector3 column = calibrationPile.GetDenominationColumnWorldPosition(0, 0);
        float chipHeight = calibrationPile.chipHeight * Mathf.Abs(calibrationPile.transform.lossyScale.y);
        Vector3 target = new Vector3(column.x,
            calibrationPile.GetDenominationColumnTopWorldY(0, 0) - chipHeight * 0.5f, column.z);

        VRCPlayerApi.TrackingData hand = local.GetTrackingData(rightHand
            ? VRCPlayerApi.TrackingDataType.RightHand : VRCPlayerApi.TrackingDataType.LeftHand);
        if ((hand.position - target).magnitude > maxHandDistance)
        {
            Say(rightHand ? "Put your right hand on the top chip" : "Put your left hand on the top chip");
            return;
        }

        Vector3 solved;
        if (!PhysicalRaiseSelectionMath.SolveHandOffset(hand.position, hand.rotation, target, out solved))
        {
            Say("Hold your hand level and try again");
            return;
        }

        float scale = PhysicalRaiseSelectionMath.ScaleFactor(local.GetAvatarEyeHeightAsMeters());
        Vector3 stored = PhysicalRaiseSelectionMath.MirrorOffsetForHand(solved / scale, rightHand);
        if (!PhysicalRaiseSelectionMath.IsPlausibleOffset(stored))
        {
            Say("Hand too far off, try again");
            return;
        }

        Vector3 previous = currentOffset;
        currentOffset = stored;
        hasOffset = true;
        PlayerData.SetVector3(PersistenceHandOffsetKey, stored);
        ApplyToPiles(stored);
        status = "Saved. Previous offset: " + Format(previous);
        RefreshLabel();
    }

    private void FillPile()
    {
        if (calibrationPile == null) return;
        int chipValue = calibrationPile.GetDenominationValue(0);
        calibrationPile.SetTotalChips(chipValue * calibrationChips);
    }

    private void ApplyToPiles(Vector3 offset)
    {
        if (piles == null) return;
        for (int i = 0; i < piles.Length; i++)
        {
            if (piles[i] != null) piles[i].SetCalibratedHandOffset(offset);
        }
    }

    private Vector3 DefaultOffset()
    {
        if (piles != null)
        {
            for (int i = 0; i < piles.Length; i++)
            {
                if (piles[i] != null) return piles[i].handOffset;
            }
        }
        return Vector3.zero;
    }

    private void ClearPiles()
    {
        if (piles == null) return;
        for (int i = 0; i < piles.Length; i++)
        {
            if (piles[i] != null) piles[i]._ClearCalibratedHandOffset();
        }
    }

    private void Say(string message)
    {
        status = message;
        RefreshLabel();
    }

    private void RefreshLabel()
    {
        if (label == null) return;
        string text = "<b>Immersive betting calibration:</b>\n"
            + "Rest either hand on the top of the pile, then press that hand's button with the other hand.\n"
            + "Current offset: " + Format(currentOffset);
        if (status != "") text += "\n" + status;
        label.text = text;
    }

    private string Format(Vector3 offset)
    {
        return "(" + Fixed3(offset.x) + ", " + Fixed3(offset.y) + ", " + Fixed3(offset.z) + ")";
    }

    private string Fixed3(float value)
    {
        int milli = Mathf.RoundToInt(Mathf.Abs(value) * 1000f);
        int fraction = milli % 1000;
        string digits = fraction.ToString();
        if (fraction < 10) digits = "00" + digits;
        else if (fraction < 100) digits = "0" + digits;
        string sign = value < 0f && milli > 0 ? "-" : "";
        return sign + (milli / 1000).ToString() + "." + digits;
    }
}
