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

/// <summary>
/// Edge cases and races around the immersive (physical) betting toggle: flipping it while a call pile is held,
/// thrown, waiting to return home, or after the bet was already committed must never leave the call pile
/// without text / stuck physical / unable to commit, and must never rewrite a committed bet.
/// </summary>
public class PhysicalBettingToggleTests
{
    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();
    }

    // ---- toggling while the pile is in use ----

    [Test]
    public void ToggleOffWhileHeld_ReleasesPileAndRestoresText()
    {
        Fixture f = Build();
        f.Player.SetPhysicalBettingEnabled(true);
        Grab(f);

        f.Player.SetPhysicalBettingEnabled(false);

        Assert.IsFalse((bool)VrcRuntimeFake.GetPrivate(f.Pile, "callActionActive"), "The call action must end");
        Assert.IsTrue(f.Chip.textGameObject.activeSelf, "The pile text must come back");
        Assert.IsTrue(f.Pile.GetComponent<Rigidbody>().isKinematic, "The pile must stop simulating");
    }

    [Test]
    public void ToggleWhilePileIsThrown_CancelsTheStaleReturnCallback()
    {
        Fixture f = Build();
        f.Player.SetPhysicalBettingEnabled(true);
        Grab(f);
        f.Pile.OnDrop(); // thrown: tracking collision, return-home callback armed
        int armedToken = (int)VrcRuntimeFake.GetPrivate(f.Pile, "pendingReturnToken");
        Assert.AreEqual(armedToken, (int)VrcRuntimeFake.GetPrivate(f.Pile, "dropToken"), "Sanity: callback armed");

        f.Player.SetPhysicalBettingEnabled(false);

        Assert.AreNotEqual((int)VrcRuntimeFake.GetPrivate(f.Pile, "pendingReturnToken"),
            (int)VrcRuntimeFake.GetPrivate(f.Pile, "dropToken"),
            "The toggle must invalidate the old return-home callback so it cannot act on the new mode");
        Assert.IsFalse((bool)VrcRuntimeFake.GetPrivate(f.Pile, "trackingCollision"),
            "A thrown pile must stop tracking the commit area after the mode flips");
    }

    [Test]
    public void StaleReturnCallback_AfterOffOnCycle_DoesNotUnlockTheLockedPile()
    {
        Fixture f = Build();
        f.Player.SetPhysicalBettingEnabled(true);
        Grab(f);
        f.Pile.OnDrop();

        f.Player.SetPhysicalBettingEnabled(false);
        f.Player.SetPhysicalBettingEnabled(true);
        Assert.IsFalse(f.Pile.pickup.pickupable, "Sanity: physical mode starts locked until it is our turn");

        f.Pile._MoveBackToInitialPosition(); // the delayed event from before the toggles fires late

        Assert.IsFalse(f.Pile.pickup.pickupable,
            "A return callback from before the toggle cycle must not make the pile grabbable out of turn");
    }

    [Test]
    public void OffOnCycle_ThenCall_StillCommits()
    {
        Fixture f = Build();
        f.Player.SetPhysicalBettingEnabled(true);
        Grab(f);
        f.Player.SetPhysicalBettingEnabled(false);
        f.Player.SetPhysicalBettingEnabled(true);

        f.Player.bet = f.Player.GetPhysicalCallAmount();
        f.Pile.SetPhysicalGrabbable(true);
        f.Pile.pickup.currentlyHeldBy = f.Pile.transform;
        f.Pile.OnPickup();
        f.Pile.transform.position = f.Target.bounds.center;
        VrcRuntimeFake.InvokeNoArg(f.Pile, "Update");

        Assert.AreEqual(f.Game.epoch, f.Player.committedEpoch,
            "After toggling off and on, carrying the call pile into the play area must still commit the call");
        Assert.IsTrue(f.Chip.textGameObject.activeSelf, "The committed pile must show its text again");
    }

    [Test]
    public void OnOffCycle_LegacyBetStillWorks()
    {
        Fixture f = Build();
        f.Player.SetPhysicalBettingEnabled(true);
        f.Player.SetPhysicalBettingEnabled(false);

        f.Pile.Interact();

        Assert.AreEqual(f.Game.epoch, f.Player.committedEpoch, "Desktop legacy confirm must work after the cycle");
    }

    [Test]
    public void RepeatedToggling_AlwaysEndsWithTextVisible()
    {
        Fixture f = Build();
        for (int i = 0; i < 8; i++)
        {
            f.Player.SetPhysicalBettingEnabled(i % 2 == 0);
            if (i % 2 == 0)
            {
                f.Pile.SetPhysicalGrabbable(true);
                f.Pile.pickup.currentlyHeldBy = f.Pile.transform;
                f.Pile.OnPickup();
            }
        }

        Assert.IsTrue(f.Chip.textGameObject.activeSelf,
            "No toggle sequence may leave the bet pile text hidden");
    }

    // ---- toggling after the action was committed ----

    [Test]
    public void ToggleOffAfterCommittedRaise_DoesNotRewriteTheBet()
    {
        Fixture f = Build();
        f.Player.SetPhysicalBettingEnabled(true);
        f.Player.bet = 300; // a committed raise above the call amount of 100
        f.Player.committedEpoch = f.Game.epoch;
        VrcRuntimeFake.SetPrivate(f.Player, "actionTaken", true);

        f.Player.SetPhysicalBettingEnabled(false);

        Assert.AreEqual(300, f.Player.bet,
            "Turning the mode off after committing must not reset the already committed bet to the call amount");
    }

    [Test]
    public void ToggleOffBeforeCommit_ResetsBetToCall()
    {
        Fixture f = Build();
        f.Player.SetPhysicalBettingEnabled(true);
        f.Player.bet = 300; // a reserved but uncommitted raise

        f.Player.SetPhysicalBettingEnabled(false);

        Assert.AreEqual(f.Player.GetPhysicalCallAmount(), f.Player.bet,
            "An uncommitted physical raise must not leak into legacy mode");
    }

    [Test]
    public void ToggleOn_WhenNotSeatedLocally_DoesNotThrow()
    {
        Fixture f = Build();
        f.Runtime.Owners.Remove(f.Player.gameObject);
        VrcRuntimeFake.SetPrivate(f.Player, "activePlayerId", -1);

        Assert.DoesNotThrow(() => f.Player.SetPhysicalBettingEnabled(true));
        Assert.DoesNotThrow(() => f.Player.SetPhysicalBettingEnabled(false));
    }

    [Test]
    public void ToggleWithNoBetPileWired_DoesNotThrow()
    {
        Fixture f = Build();
        f.Player.grabbableBetPile = null;

        Assert.DoesNotThrow(() => f.Player.SetPhysicalBettingEnabled(true));
        Assert.DoesNotThrow(() => f.Player.SetPhysicalBettingEnabled(false));
    }

    // ---- call flow after toggling, in both chip presentation modes ----

    [TestCase(false, 0)]
    [TestCase(false, 1)]
    [TestCase(false, 2)]
    [TestCase(false, 3)]
    [TestCase(true, 0)]
    [TestCase(true, 1)]
    [TestCase(true, 2)]
    [TestCase(true, 3)]
    public void CallAfterImmersiveToggling_CommitsAndShowsTextInEveryChipMode(bool animatedChips, int toggles)
    {
        Fixture f = Build();
        AddChipRig(f, animatedChips);
        bool physical = toggles % 2 == 1;
        for (int i = 0; i < toggles; i++) f.Player.SetPhysicalBettingEnabled(i % 2 == 0);

        int call = f.Player.GetPhysicalCallAmount();
        f.Player.bet = call;
        f.Chip.SetTotalChips(call);
        f.Pile.pickup.currentlyHeldBy = f.Pile.transform;
        if (physical)
        {
            f.Pile.SetPhysicalGrabbable(true);
            f.Pile.OnPickup();
        }
        else
        {
            runtime.VrUsers[runtime.LocalPlayer.playerId] = true; // VR: grab and throw, desktop just uses Interact
            f.Pile.SetGrabbable(true);
            f.Pile.OnPickup();
            f.Pile.OnDrop();
        }
        f.Pile.transform.position = f.Target.bounds.center;
        VrcRuntimeFake.InvokeNoArg(f.Pile, "Update");

        Assert.AreEqual(f.Game.epoch, f.Player.committedEpoch,
            "Bringing the call pile into the play area must commit the call (physical=" + physical +
            ", animated=" + animatedChips + ", toggles=" + toggles + "); otherwise the chips just return home");
        Assert.IsTrue(f.Chip.textGameObject.activeSelf, "The call pile must have its text after the commit");
        if (physical && animatedChips)
            Assert.AreEqual(call, f.Player.roundContributionPile.GetTotalDisplayedValue(),
                "An animated physical call must move the chips into the round pile");
    }

    [TestCase(false)]
    [TestCase(true)]
    public void ToggleBackAndForthWhileCallPileIsHeld_ThenCall_StillWorks(bool animatedChips)
    {
        Fixture f = Build();
        AddChipRig(f, animatedChips);
        f.Player.SetPhysicalBettingEnabled(true);
        Grab(f);
        f.Player.SetPhysicalBettingEnabled(false);
        f.Player.SetPhysicalBettingEnabled(true);

        Grab(f);
        f.Pile.transform.position = f.Target.bounds.center;
        VrcRuntimeFake.InvokeNoArg(f.Pile, "Update");

        Assert.AreEqual(f.Game.epoch, f.Player.committedEpoch);
        Assert.IsTrue(f.Chip.textGameObject.activeSelf);
    }

    // ---- mode-dependent state that is only set up at the start of a turn ----

    [Test]
    public void ToggleOffMidTurn_BringsTheBettingControlsBack()
    {
        Fixture f = Build();
        BettingUi ui = AttachBettingUi(f);
        f.Player.SetPhysicalBettingEnabled(true);
        ui.HideBettingControls(); // what the turn-start edge does in physical mode

        f.Player.SetPhysicalBettingEnabled(false);

        Assert.IsTrue(ui.resetButton.activeSelf,
            "Leaving immersive mode on our own turn must restore the legacy betting buttons; " +
            "they are only (re)built at the turn-start edge, so the UI would come back empty");
        Assert.IsTrue(AnyButtonActive(ui), "At least one chip button must be shown again");
    }

    [Test]
    public void ToggleOffMidTurn_AfterStartingTurnInPhysicalMode_ThenBackOn_HidesThemAgain()
    {
        Fixture f = Build();
        BettingUi ui = AttachBettingUi(f);
        f.Player.SetPhysicalBettingEnabled(true);
        ui.HideBettingControls();
        f.Player.SetPhysicalBettingEnabled(false);
        f.Player.SetPhysicalBettingEnabled(true);

        Assert.IsFalse(AnyButtonActive(ui) || ui.resetButton.activeSelf,
            "Physical mode must not leave the legacy chip buttons visible");
    }

    [Test]
    public void ToggleOffMidTurn_WhenCallOnly_KeepsControlsHidden()
    {
        Fixture f = Build();
        f.Game.callOnlyMask = 1 << 0;
        BettingUi ui = AttachBettingUi(f);
        f.Player.SetPhysicalBettingEnabled(true);
        ui.HideBettingControls();

        f.Player.SetPhysicalBettingEnabled(false);

        Assert.IsFalse(AnyButtonActive(ui) || ui.resetButton.activeSelf,
            "A call-only seat never gets raise buttons, in either mode");
    }

    [Test]
    public void ToggleOffWhenNotActing_DoesNotShowControls()
    {
        Fixture f = Build();
        f.Game.playerState[0] = HoldemGame.PLAYER_PENDING;
        BettingUi ui = AttachBettingUi(f);
        f.Player.SetPhysicalBettingEnabled(true);
        ui.HideBettingControls();

        f.Player.SetPhysicalBettingEnabled(false);

        Assert.IsFalse(AnyButtonActive(ui), "Nothing to show while it is not our turn");
    }

    [Test]
    public void ToggleOnMidTurn_DropsAStaleLegacyBet()
    {
        Fixture f = Build();
        f.Player.bet = 300; // raised with the legacy buttons before the toggle

        f.Player.SetPhysicalBettingEnabled(true);

        Assert.AreEqual(f.Player.GetPhysicalCallAmount(), f.Player.bet,
            "Entering immersive mode starts from a plain call, as at the start of a turn; a stale legacy raise " +
            "would otherwise be added to whatever chips the player then drags");
    }

    [Test]
    public void ToggleOnMidTurn_ThenIncrease_DoesNotCompoundTheStaleBet()
    {
        Fixture f = Build();
        f.Player.bet = 300;
        f.Player.SetPhysicalBettingEnabled(true);

        f.Player.ApplyPhysicalIncrease(100);

        Assert.AreEqual(f.Player.GetPhysicalCallAmount() + 100, f.Player.bet,
            "A 100 chip increase from a call must land on call + 100");
    }

    // ---- helpers ----

    private class Fixture
    {
        public VrcRuntimeFake Runtime;
        public HoldemGame Game;
        public HoldemPlayer Player;
        public GrabbablePile Pile;
        public PokerChipPile Chip;
        public BoxCollider Target;
    }

    // Gives the fixture a real chip pile for the call pile plus a round pile, in the requested presentation mode.
    private void AddChipRig(Fixture f, bool animatedChips)
    {
        GameObject poolObject = Spawn("Pool");
        LocalObjectPool pool = poolObject.AddComponent<LocalObjectPool>();
        pool.denomination = 5;
        pool.Pool = new GameObject[60];
        for (int i = 0; i < pool.Pool.Length; i++)
        {
            GameObject chip = Spawn("Chip" + i);
            chip.transform.SetParent(poolObject.transform);
            Rigidbody body = chip.AddComponent<Rigidbody>();
            body.isKinematic = true;
            body.useGravity = false;
            chip.AddComponent<BoxCollider>().enabled = false;
            pool.Pool[i] = chip;
        }
        VrcRuntimeFake.InvokeNoArg(pool, "Start");

        f.Chip.denominationValues = new[] { 5 };
        f.Chip.denominationPools = new[] { pool };
        f.Chip.gatherTransportDuration = 0f;
        VrcRuntimeFake.InvokeNoArg(f.Chip, "Start");
        f.Player.betPile = f.Chip;

        PokerChipPile round = Spawn("Round").AddComponent<PokerChipPile>();
        round.denominationValues = new[] { 5 };
        round.denominationPools = new[] { pool };
        round.gatherTransportDuration = 0f;
        VrcRuntimeFake.InvokeNoArg(round, "Start");
        f.Player.roundContributionPile = round;

        f.Game.seats = 1;
        f.Game.tableState = HoldemGame.TABLE_PLAYING;
        f.Game.players = new[] { f.Player };
        f.Game.potPile = null;
        f.Game.SetAnimatedChipContainersEnabled(animatedChips);
    }

    private BettingUi AttachBettingUi(Fixture f)
    {
        GameObject uiObject = Spawn("BettingUi");
        BettingUi ui = uiObject.AddComponent<BettingUi>();
        ui.denominations = new[] { 5, 25, 100, 500, 2500 };
        ui.buttons = new GameObject[5];
        for (int i = 0; i < ui.buttons.Length; i++)
        {
            ui.buttons[i] = Spawn("Button" + i);
            ui.buttons[i].transform.SetParent(uiObject.transform);
            ui.buttons[i].SetActive(false);
        }
        ui.positions = new Transform[3];
        for (int i = 0; i < ui.positions.Length; i++)
            ui.positions[i] = Spawn("Pos" + i).transform;
        ui.resetButton = Spawn("Reset");
        ui.resetButton.SetActive(false);
        f.Player.bettingUi = ui;
        return ui;
    }

    private static bool AnyButtonActive(BettingUi ui)
    {
        for (int i = 0; i < ui.buttons.Length; i++)
            if (ui.buttons[i].activeSelf) return true;
        return false;
    }

    private void Grab(Fixture f)
    {
        f.Player.bet = f.Player.GetPhysicalCallAmount();
        f.Pile.SetPhysicalGrabbable(true);
        f.Pile.pickup.currentlyHeldBy = f.Pile.transform;
        f.Pile.OnPickup();
        Assert.IsFalse(f.Chip.textGameObject.activeSelf, "Sanity: grabbing hides the text");
    }

    private Fixture Build()
    {
        Fixture f = new Fixture { Runtime = runtime };
        f.Game = Spawn("Game").AddComponent<HoldemGame>();
        f.Game.playerState = new int[HoldemGame.MAX_SEATS];
        f.Game.stacks = new int[HoldemGame.MAX_SEATS];
        f.Game.roundContribution = new int[HoldemGame.MAX_SEATS];
        f.Game.playerState[0] = HoldemGame.PLAYER_ACTING;
        f.Game.playerState[1] = HoldemGame.PLAYER_PENDING;
        f.Game.stacks[0] = 1000;
        f.Game.stacks[1] = 1000;
        f.Game.currentBet = 100;
        f.Game.minimumRaise = 100;
        f.Game.actingSeat = 0;
        f.Game.aggressorSeat = 1;
        f.Game.epoch = 7;

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

        GameObject targetObject = Spawn("BetTarget");
        targetObject.transform.position = new Vector3(0f, 0f, 2f);
        f.Target = targetObject.AddComponent<BoxCollider>();
        f.Target.size = Vector3.one;

        GameObject pileObject = Spawn("CallPile");
        Rigidbody body = pileObject.AddComponent<Rigidbody>();
        body.isKinematic = true;
        body.useGravity = false;
        BoxCollider ownCollider = pileObject.AddComponent<BoxCollider>();
        Type pickupType = Type.GetType("VRC.SDK3.Components.VRCPickup, VRCSDK3");
        Assert.IsNotNull(pickupType, "VRCPickup SDK component type was not loaded");
        VRC_Pickup pickup = (VRC_Pickup)pileObject.AddComponent(pickupType);
        f.Pile = pileObject.AddComponent<GrabbablePile>();
        f.Pile.pickup = pickup;
        f.Pile.player = f.Player;
        f.Pile.targetCollider = f.Target;
        f.Pile.ownCollider = ownCollider;
        f.Player.grabbableBetPile = f.Pile;
        runtime.Owners[pileObject] = runtime.LocalPlayer;

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

        VrcRuntimeFake.InvokeNoArg(f.Pile, "Start");
        return f;
    }

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