using UdonSharp;
using UnityEngine;

// Tournament lifecycle, prize distribution, and lobby-settings button handlers
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class HoldemTournament : UdonSharpBehaviour
{
    // Pays out the prize pool to ranks 1..3. Expects playerRanks to already be assigned.
    // Remainders land on the top prize so the whole pool is always distributed.
    public static void DistributeTournamentPrizes(HoldemGame game, int winnerSeat)
    {
        int totalPool = game.totalParticipants * game.tournamentBuyIn;
        Debug.Log($"[Holdem] Tournament ending. Issuing payouts from pool of {totalPool}. Winner: Seat {winnerSeat}");

        // Second place is paid from 3 players up, third from 4
        int secondSeat = game.totalParticipants >= 3 ? FindSeatWithRank(game, 2) : -1;
        int thirdSeat = game.totalParticipants >= 4 ? FindSeatWithRank(game, 3) : -1;
        int second = secondSeat != -1 ? totalPool * 30 / 100 : 0;
        int third = thirdSeat != -1 ? totalPool * 10 / 100 : 0;

        HoldemBalanceOps.AwardTournamentPayout(game, winnerSeat, totalPool - second - third);
        if (secondSeat != -1) HoldemBalanceOps.AwardTournamentPayout(game, secondSeat, second);
        if (thirdSeat != -1) HoldemBalanceOps.AwardTournamentPayout(game, thirdSeat, third);
    }

    public static int FindSeatWithRank(HoldemGame game, int rank)
    {
        for (int i = 0; i < game.seats; i++)
        {
            if (game.playerRanks[i] == rank)
            {
                return i;
            }
        }
        return -1;
    }

    private static int ActiveCount(HoldemGame game)
    {
        int count = 0;
        for (int i = 0; i < game.seats; i++)
        {
            if (!game.tournamentEliminated[i]) count++;
        }
        return count;
    }

    private static int FirstActiveSeat(HoldemGame game)
    {
        for (int i = 0; i < game.seats; i++)
        {
            if (!game.tournamentEliminated[i]) return i;
        }
        return -1;
    }

    // Orders the first count entries of seatList by key[seat]
    private static void SortSeatsByKey(int[] seatList, int count, int[] key, bool descending)
    {
        for (int i = 0; i < count - 1; i++)
        {
            for (int j = i + 1; j < count; j++)
            {
                int a = key[seatList[i]];
                int b = key[seatList[j]];
                if (descending ? a < b : a > b)
                {
                    int temp = seatList[i];
                    seatList[i] = seatList[j];
                    seatList[j] = temp;
                }
            }
        }
    }

    public static void AdjustBuyIn(HoldemGame game, int direction)
    {
        game.tournamentBuyIn = Mathf.Clamp(game.tournamentBuyIn + 500 * direction, 500, 100000);
        game.RequestSerialization();
    }

    public static void AdjustStartingStack(HoldemGame game, int direction)
    {
        game.tournamentStartingStack = Mathf.Clamp(game.tournamentStartingStack + 1000 * direction, 1000, 500000);
        game.RequestSerialization();
    }

    // One minute steps, between 1 and 60 minutes
    public static void AdjustBlindTimer(HoldemGame game, int direction)
    {
        game.tournamentLevelDurationSeconds = Mathf.Clamp(game.tournamentLevelDurationSeconds + 60f * direction, 60f, 3600f);
        game.RequestSerialization();
    }

    public static void EndTournament(HoldemGame game)
    {
        game.isTournamentActive = false;
        game.bigBlind = game.minBigBlind;

        for (int i = 0; i < game.seats; i++)
        {
            if (game.players[i] != null && game.players[i].IsSeated())
            {
                game.players[i]._ReleaseControl();
            }
            game.wasSeated[i] = false;
            game.tournamentPlayerNames[i] = "";
            game.tournamentPlayerIds[i] = 0;
        }
    }

    // Validates and sets up a new tournament
    public static bool TryStartTournament(HoldemGame game)
    {
        int seatedCount = 0;
        for (int i = 0; i < game.seats; i++)
        {
            if (game.players[i].IsSeated())
            {
                if (HoldemBalanceOps.GetBalanceForSeat(game, i) < game.tournamentBuyIn)
                {
                    Debug.Log($"[Holdem] Cannot start: Player in seat {i} doesn't have the buy-in of {game.tournamentBuyIn}");
                    return false;
                }
                seatedCount++;
            }
        }

        if (seatedCount < 2)
        {
            Debug.Log("[Holdem] Need at least 2 players to start a tournament.");
            return false;
        }

        game.totalParticipants = seatedCount;
        for (int i = 0; i < game.seats; i++)
        {
            if (game.players[i].IsSeated())
            {
                PlayerBalanceComponent BalanceComponent = HoldemBalanceOps.GetSeatBalanceComponent(game, i);
                // Remembered for the whole tournament so a prize or refund still reaches them
                // if they stand up, or the master changes, before it's awarded.
                game.tournamentPlayerIds[i] = game.players[i].ActivePlayerId();
                HoldemBalanceOps.ModifyBalanceForSeat(game, i, -game.tournamentBuyIn);
                if (BalanceComponent)
                {
                    BalanceComponent.RecordProfit(-game.tournamentBuyIn);
                }
                game.stacks[i] = game.tournamentStartingStack;
                game.tournamentEliminated[i] = false;
                game.playerRanks[i] = 0;
                game.tournamentPlayerNames[i] = game.players[i].OwnerName();
                // Force player ready so they are dealt in immediately
                game.players[i].playerReady = true;
                game.players[i].RequestSerialization();
            }
            else
            {
                game.stacks[i] = 0;
                game.tournamentEliminated[i] = true;
                game.playerRanks[i] = 0;
                game.tournamentPlayerNames[i] = "";
                game.tournamentPlayerIds[i] = 0;
            }
        }

        game.currentBlindLevelIndex = 0;
        game.blindLevelStartMillis = game.GetTimeMillis();
        game.isTournamentActive = true;

        Debug.Log($"[Holdem] Tournament started with {game.totalParticipants} players! Buy-in: {game.tournamentBuyIn}, Starting stack: {game.tournamentStartingStack}");

        return true;
    }

    public static void CancelTournament(HoldemGame game)
    {
        for (int i = 0; i < game.seats; i++)
        {
            if (!game.tournamentEliminated[i] && game.tournamentPlayerNames[i] != "")
            {
                HoldemBalanceOps.AwardTournamentPayout(game, i, game.tournamentBuyIn);
            }
        }

        EndTournament(game);
        Debug.Log("[Holdem] Tournament cancelled and refunds issued to active players.");
    }

    public static void ToggleTournamentMode(HoldemGame game)
    {
        game.isTournamentMode = !game.isTournamentMode;
        if (!game.isTournamentMode)
        {
            for (int i = 0; i < game.seats; i++)
            {
                game.wasSeated[i] = false; // Reset stack initialization
            }
        }
        Debug.Log($"[Holdem] Tournament mode toggled to {game.isTournamentMode}");
    }

    public static bool TryResolveAbandonedTournament(HoldemGame game, bool[] playerIsSeated)
    {
        if (!game.isTournamentActive) return false;

        int totalActiveCount = 0;
        int seatedActiveCount = 0;
        for (int i = 0; i < game.seats; i++)
        {
            if (!game.tournamentEliminated[i])
            {
                totalActiveCount++;
                if (playerIsSeated[i])
                {
                    seatedActiveCount++;
                }
            }
        }

        bool walkedOut = false;
        if (totalActiveCount > 1 && seatedActiveCount <= 1)
        {
            if (!game.noSeatedActiveArmed)
            {
                game.noSeatedActiveArmed = true;
                game.noSeatedActiveSinceMillis = game.GetTimeMillis();
            }
            walkedOut = (game.GetTimeMillis() - game.noSeatedActiveSinceMillis) / 1000 > game.abandonedTournamentTimeoutSecs;
        }
        else
        {
            game.noSeatedActiveArmed = false;
        }

        if (!walkedOut) return false;

        int winnerSeat = -1;
        for (int i = 0; i < game.seats; i++)
        {
            if (!game.tournamentEliminated[i] && playerIsSeated[i])
            {
                winnerSeat = i;
                break;
            }
        }

        if (winnerSeat == -1)
        {
            for (int i = 0; i < game.seats; i++)
            {
                if (!game.tournamentEliminated[i] && (winnerSeat == -1 || game.stacks[i] > game.stacks[winnerSeat]))
                {
                    winnerSeat = i;
                }
            }
            Debug.Log($"[Holdem] Tournament abandoned with nobody seated; resolving on stack size. Winner: Seat {winnerSeat}");
        }

        if (winnerSeat == -1) return false;

        int[] unseatedActiveSeats = new int[HoldemGame.MAX_SEATS];
        int unseatedCount = 0;
        for (int i = 0; i < game.seats; i++)
        {
            if (!game.tournamentEliminated[i] && !playerIsSeated[i] && i != winnerSeat)
            {
                unseatedActiveSeats[unseatedCount] = i;
                unseatedCount++;
            }
        }

        SortSeatsByKey(unseatedActiveSeats, unseatedCount, game.stacks, true);

        // Assign ranks starting from 2 to unseated active players
        for (int i = 0; i < unseatedCount; i++)
        {
            int seatIdx = unseatedActiveSeats[i];
            game.tournamentEliminated[seatIdx] = true;
            game.playerRanks[seatIdx] = 2 + i;
            Debug.Log($"[Holdem] Seat {seatIdx} left the join (unseated) and is ranked {game.playerRanks[seatIdx]} with stack {game.stacks[seatIdx]}");
        }

        game.playerRanks[winnerSeat] = 1;
        Debug.Log($"[Holdem] Tournament Finished early! All but one player left. Winner: Seat {winnerSeat}");

        DistributeTournamentPrizes(game, winnerSeat);

        // Reset table and tournament state to IDLE
        EndTournament(game);
        game._ResetHandState();
        game.tableState = HoldemGame.TABLE_IDLE;

        return true;
    }

    public static void AdvanceBlindLevel(HoldemGame game)
    {
        int timeElapsed = game.GetTimeMillis() - game.blindLevelStartMillis;
        if (timeElapsed >= game.tournamentLevelDurationSeconds * 1000)
        {
            game.currentBlindLevelIndex++;
            if (game.currentBlindLevelIndex >= game.tournamentBlindLevels.Length)
            {
                game.currentBlindLevelIndex = game.tournamentBlindLevels.Length - 1;
            }
            game.bigBlind = game.tournamentBlindLevels[game.currentBlindLevelIndex];
            game.blindLevelStartMillis += (int)(game.tournamentLevelDurationSeconds * 1000);
            Debug.Log($"[Holdem] Tournament blind level increased to Level {game.currentBlindLevelIndex + 1}. New BB: {game.bigBlind}");
        }
        else
        {
            game.bigBlind = game.tournamentBlindLevels[game.currentBlindLevelIndex];
        }
    }

    public static void CheckHandEliminations(HoldemGame game)
    {
        int currentlyActive = ActiveCount(game);

        int[] newlyEliminated = new int[HoldemGame.MAX_SEATS];
        int elimCount = 0;
        for (int i = 0; i < game.seats; i++)
        {
            if (!game.tournamentEliminated[i] && game.stacks[i] <= 0)
            {
                newlyEliminated[elimCount++] = i;
            }
        }

        if (elimCount > 0)
        {
            // Whoever brought fewer chips to the hand busts first (worse rank)
            SortSeatsByKey(newlyEliminated, elimCount, game.handStartStacks, false);

            for (int i = 0; i < elimCount; i++)
            {
                int seatIdx = newlyEliminated[i];
                game.tournamentEliminated[seatIdx] = true;
                game.playerRanks[seatIdx] = currentlyActive;
                currentlyActive--;
                Debug.Log($"[Holdem] Seat {seatIdx} is eliminated in Rank {game.playerRanks[seatIdx]}!");
                if (game.players[seatIdx] != null && game.players[seatIdx].IsSeated())
                {
                    game.players[seatIdx]._ReleaseControl();
                }
            }

            game.blindLevelStartMillis -= elimCount * (int)(game.eliminationBlindTimerCutSeconds * 1000);
        }

        // Check if tournament is over
        if (currentlyActive <= 1)
        {
            int winnerSeat = FirstActiveSeat(game);
            if (winnerSeat != -1)
            {
                game.playerRanks[winnerSeat] = 1;
                Debug.Log($"[Holdem] Tournament Finished! Winner: Seat {winnerSeat}");
            }
        }
    }

    public static bool TryEndTournamentAtIdle(HoldemGame game)
    {
        if (ActiveCount(game) > 1) return false;

        int winnerSeat = FirstActiveSeat(game);
        if (winnerSeat != -1)
        {
            game.playerRanks[winnerSeat] = 1;
            DistributeTournamentPrizes(game, winnerSeat);
        }

        EndTournament(game);
        return true;
    }
}
