using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using UnityEngine;
using VRC.SDKBase;

/// <summary>
/// Regression tests for the call pile lifecycle around committing a bet.
/// A committed call pile must stop simulating and get its text back, the
/// next-turn reset must restore the text, and the legacy Interact confirm
/// must only fire on desktop (VR players confirm by throwing chips).
/// </summary>
public class GrabbablePileResetTests
{
    private readonly List<GameObject> objects = new List<GameObject>();
    private VrcRuntimeFake runtime;
    private object originalPickupHand;

    [SetUp]
    public void SetUp()
    {
        runtime = new VrcRuntimeFake();
        runtime.Install();

        FieldInfo pickupHand = typeof(VRC_Pickup).GetField("_GetPickupHand",
            BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
        originalPickupHand = pickupHand.GetValue(null);
        pickupHand.SetValue(null,
            new Func<VRC_Pickup, VRC_Pickup.PickupHand>(_ => VRC_Pickup.PickupHand.Right));
    }

    [TearDown]
    public void TearDown()
    {
        FieldInfo pickupHand = typeof(VRC_Pickup).GetField("_GetPickupHand",
            BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
        pickupHand.SetValue(null, originalPickupHand);
        runtime.Uninstall();
        for (int i = objects.Count - 1; i >= 0; i--)
            if (objects[i] != null) UnityEngine.Object.DestroyImmediate(objects[i]);
        objects.Clear();
    }

    [Test]
    public void Interact_DoesNotConfirmInVR()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        GrabbablePile pile = BuildCallPile(player, BuildTarget());
        runtime.VrUsers[runtime.LocalPlayer.playerId] = true;

        pile.Interact();

        Assert.AreEqual(-1, player.committedEpoch,
            "The VR use button must not confirm the bet");
    }

    [Test]
    public void Interact_ConfirmsOnDesktop()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        GrabbablePile pile = BuildCallPile(player, BuildTarget());

        pile.Interact();

        Assert.AreEqual(game.epoch, player.committedEpoch,
            "Desktop interact must still confirm the bet");
    }

    [Test]
    public void PhysicalCallCommit_RestoresTextVisibility()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        BoxCollider target = BuildTarget();
        GrabbablePile pile = BuildCallPile(player, target);
        GameObject textObject = pile.GetComponent<PokerChipPile>().textGameObject;

        EnterPlayAreaHeld(pile, player, target);

        Assert.AreEqual(game.epoch, player.committedEpoch, "Sanity: the call must commit");
        Assert.IsTrue(textObject.activeSelf,
            "A committed call pile must get its text back");
    }

    [Test]
    public void PhysicalCallCommit_DisablesPhysics()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        BoxCollider target = BuildTarget();
        GrabbablePile pile = BuildCallPile(player, target);
        Rigidbody body = pile.GetComponent<Rigidbody>();

        EnterPlayAreaHeld(pile, player, target);

        Assert.AreEqual(game.epoch, player.committedEpoch, "Sanity: the call must commit");
        Assert.IsTrue(body.isKinematic,
            "A committed call pile must stop simulating so it stays where it landed");
        Assert.IsFalse(body.useGravity);
    }

    [Test]
    public void ResetPhysicalBetToCallDisplay_RestoresTextVisibility()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        GrabbablePile pile = BuildCallPile(player, BuildTarget());
        PokerChipPile chipPile = pile.GetComponent<PokerChipPile>();

        player.SetPhysicalBettingEnabled(true);
        chipPile.SetTextVisibility(false); // what OnPickup does at grab time
        Assert.IsFalse(chipPile.textGameObject.activeSelf);

        pile._ResetPhysicalBetToCallDisplay();

        Assert.IsTrue(chipPile.textGameObject.activeSelf,
            "The next-turn reset must restore the pile text");
    }

    [Test]
    public void ThrownCallCommit_DoesNotCancelReturnHome()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        BoxCollider target = BuildTarget();
        GrabbablePile pile = BuildCallPile(player, target);

        player.SetPhysicalBettingEnabled(true);
        player.bet = player.GetPhysicalCallAmount();
        pile.SetPhysicalGrabbable(true);

        pile.pickup.currentlyHeldBy = pile.transform;
        pile.OnPickup();
        VrcRuntimeFake.SetPrivate(pile, "callActionActive", false);
        VrcRuntimeFake.SetPrivate(pile, "trackingCollision", true);
        VrcRuntimeFake.SetPrivate(pile, "pendingReturnToken",
            VrcRuntimeFake.GetPrivate(pile, "dropToken"));

        pile.transform.position = target.bounds.center;
        VrcRuntimeFake.InvokeNoArg(pile, "Update");
        Assert.AreEqual(game.epoch, player.committedEpoch, "Sanity: the call must commit");

        Assert.AreEqual((int)VrcRuntimeFake.GetPrivate(pile, "dropToken"),
            (int)VrcRuntimeFake.GetPrivate(pile, "pendingReturnToken"),
            "A committed throw must not cancel the return-home callback");
    }

    [Test]
    public void HeldCallCommit_ArmsReturnHomeCallback()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        BoxCollider target = BuildTarget();
        GrabbablePile pile = BuildCallPile(player, target);

        EnterPlayAreaHeld(pile, player, target);
        Assert.AreEqual(game.epoch, player.committedEpoch, "Sanity: the call must commit");

        Assert.AreEqual((int)VrcRuntimeFake.GetPrivate(pile, "dropToken"),
            (int)VrcRuntimeFake.GetPrivate(pile, "pendingReturnToken"),
            "A held commit must arm the return-home callback so the pile respawns home");
    }

    [Test]
    public void BetweenTurnsDisable_KeepsReturnHomeCallbackArmed()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        BoxCollider target = BuildTarget();
        GrabbablePile pile = BuildCallPile(player, target);

        EnterPlayAreaHeld(pile, player, target);
        Assert.AreEqual(game.epoch, player.committedEpoch, "Sanity: the call must commit");

        pile.SetPhysicalGrabbable(false);
        Assert.IsFalse(pile.ownCollider.enabled, "Sanity: the pile must be disabled between turns");

        Assert.AreEqual((int)VrcRuntimeFake.GetPrivate(pile, "dropToken"),
            (int)VrcRuntimeFake.GetPrivate(pile, "pendingReturnToken"),
            "The between-turns disable must not cancel the return-home callback");
    }

    [Test]
    public void ReturnHomeCallback_AfterBetweenTurnsDisable_ParksPileUntilNextTurn()
    {
        HoldemGame game;
        HoldemPlayer player;
        BuildGameAndPlayer(1000, out game, out player);
        BoxCollider target = BuildTarget();
        GrabbablePile pile = BuildCallPile(player, target);
        Rigidbody body = pile.GetComponent<Rigidbody>();
        PokerChipPile chipPile = pile.GetComponent<PokerChipPile>();

        EnterPlayAreaHeld(pile, player, target);
        Assert.AreEqual(game.epoch, player.committedEpoch, "Sanity: the call must commit");

        pile.SetPhysicalGrabbable(false);
        pile._MoveBackToInitialPosition();

        Assert.IsTrue(body.isKinematic, "The returned pile must stay parked through other turns");
        Assert.IsTrue(chipPile.textGameObject.activeSelf, "The returned pile must keep its text");
        Assert.IsFalse(pile.pickup.pickupable,
            "The parked pile must stay locked while other players act");

        VrcRuntimeFake.SetPrivate(player, "actionTaken", false);
        pile.SetPhysicalGrabbable(true);
        Assert.IsTrue(pile.ownCollider.enabled, "The pile must be grabbable again on the next turn");
        Assert.IsTrue(pile.pickup.pickupable, "The pile must be pickupable again on the next turn");
    }

    /// <summary>Grab the pile, then carry it into the play area while still held.</summary>
    private void EnterPlayAreaHeld(GrabbablePile pile, HoldemPlayer player, BoxCollider target)
    {
        player.SetPhysicalBettingEnabled(true);
        player.bet = player.GetPhysicalCallAmount();
        pile.SetPhysicalGrabbable(true);

        pile.pickup.currentlyHeldBy = pile.transform;
        pile.OnPickup();
        Assert.IsFalse(pile.GetComponent<PokerChipPile>().textGameObject.activeSelf,
            "Sanity: grabbing must hide the pile text");
        Assert.IsFalse(pile.GetComponent<Rigidbody>().isKinematic,
            "Sanity: grabbing must enable physical motion");

        pile.transform.position = target.bounds.center;
        VrcRuntimeFake.InvokeNoArg(pile, "Update");
    }

    private void BuildGameAndPlayer(int stack, out HoldemGame game, out HoldemPlayer player)
    {
        game = Spawn("Game").AddComponent<HoldemGame>();
        game.playerState = new int[HoldemGame.MAX_SEATS];
        game.stacks = new int[HoldemGame.MAX_SEATS];
        game.roundContribution = new int[HoldemGame.MAX_SEATS];
        game.playerState[0] = HoldemGame.PLAYER_ACTING;
        game.playerState[1] = HoldemGame.PLAYER_PENDING;
        game.stacks[0] = stack;
        game.stacks[1] = 1000;
        game.currentBet = 100;
        game.minimumRaise = 100;
        game.actingSeat = 0;
        game.aggressorSeat = 1;
        game.epoch = 7;

        GameObject playerObject = Spawn("Player");
        player = playerObject.AddComponent<HoldemPlayer>();
        player.game = game;
        player.seatIdx = 0;
        runtime.Owners[playerObject] = runtime.LocalPlayer;
        VrcRuntimeFake.SetPrivate(player, "activePlayerId", runtime.LocalPlayer.playerId);
    }

    private GrabbablePile BuildCallPile(HoldemPlayer player, BoxCollider target)
    {
        GameObject pileObject = Spawn("CallPile");
        Rigidbody body = pileObject.AddComponent<Rigidbody>();
        body.isKinematic = true;
        body.useGravity = false;
        BoxCollider ownCollider = pileObject.AddComponent<BoxCollider>();
        VRC_Pickup pickup = AddPickup(pileObject);
        GrabbablePile pile = pileObject.AddComponent<GrabbablePile>();
        pile.pickup = pickup;
        pile.player = player;
        pile.targetCollider = target;
        pile.ownCollider = ownCollider;
        player.grabbableBetPile = pile;
        runtime.Owners[pileObject] = runtime.LocalPlayer;

        PokerChipPile chipPile = pileObject.AddComponent<PokerChipPile>();
        GameObject textObject = Spawn("PileText");
        textObject.transform.SetParent(pileObject.transform);
        chipPile.textGameObject = textObject;

        VrcRuntimeFake.InvokeNoArg(pile, "Start");
        return pile;
    }

    private BoxCollider BuildTarget()
    {
        GameObject targetObject = Spawn("BetTarget");
        targetObject.transform.position = new Vector3(0f, 0f, 2f);
        BoxCollider target = targetObject.AddComponent<BoxCollider>();
        target.size = Vector3.one;
        return target;
    }

    private VRC_Pickup AddPickup(GameObject target)
    {
        Type type = Type.GetType("VRC.SDK3.Components.VRCPickup, VRCSDK3");
        Assert.IsNotNull(type, "VRCPickup SDK component type was not loaded");
        return (VRC_Pickup)target.AddComponent(type);
    }

    private GameObject Spawn(string name)
    {
        GameObject go = new GameObject(name);
        objects.Add(go);
        return go;
    }
}
