﻿using System;
using System.Collections.Generic;
using UdonSharp;
using UnityEngine;
using UnityEngine.SocialPlatforms;
using VRC.SDK3.Persistence;
using VRC.SDKBase;
using VRC.Udon;

public enum EWelfareStatus
{
    Locked, //Represents a locked state pending the receipt of player data.
    Available, //Represents welfare is available for collection.
    Cooldown //Represents welfare is unavailable because it's on cooldown.
}

//Base component for types of welfare. Any implementer still speaks to the same welfare timer.
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class WelfareComponent : UdonSharpBehaviour
{
    //Cooldown for this welfare component in minutes.
    [SerializeField]
    protected int Cooldown = 5;

    //Maximum balance threshold - welfare is locked if player has this much or more.
    [SerializeField]
    protected int MaxBalanceThreshold = 2000;

    private int CooldownSeconds;
    
    [SerializeField]
    protected WelfareListenerComponent[] ListenerComponentList = null;

    private EWelfareStatus WelfareStatus = EWelfareStatus.Locked;
    private bool bHasReceivedPlayerData = false;
    private bool bCooldownExpireTimerActive = false;
    private PlayerBalanceComponent localPlayerBalance = null;
    
    public bool HasReceivedPlayerData() { return bHasReceivedPlayerData; }
    public EWelfareStatus GetWelfareStatus() { return WelfareStatus; }
    public int GetCooldownDuration() { return CooldownSeconds; }
    
    public virtual void Start()
    {
        CooldownSeconds = Cooldown * 60;

        // Note: Subscription to balance changes happens in OnPlayerRestored when player data is ready
    }

    public void OnBalanceChanged()
    {
        UpdateWelfareState();
    }

    //It would be nice to have a centralized "welfare manager component".
    //Would allow for it to collect all welfare components in the scene and inform them when welfare claim time changes.
    // 
    // OPTIMIZATION: Removed Update() polling - now uses event-driven updates via:
    // 1. OnPlayerRestored for initialization
    // 2. OnPlayerDataUpdated for balance/cooldown changes
    // 3. SendCustomEventDelayedSeconds for cooldown timer checking

    /// <summary>
    /// Called when PlayerData is updated for the local player.
    /// This includes balance changes which may affect welfare availability.
    /// </summary>
    public override void OnPlayerDataUpdated(VRC.SDKBase.VRCPlayerApi player, VRC.SDK3.Persistence.PlayerData.Info[] infos)
    {
        if (player != null && player.isLocal && bHasReceivedPlayerData)
        {
            UpdateWelfareState();
        }
    }

    public override void OnPlayerRestored(VRC.SDKBase.VRCPlayerApi Player)
    {
        if (!Player.isLocal)
        {
            return;
        }
        
        bHasReceivedPlayerData = true;
        
        // Subscribe to balance change events when player data is ready
        if (localPlayerBalance == null)
        {
            localPlayerBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(Player);
            if (localPlayerBalance)
            {
                localPlayerBalance.SubscribeToBalanceChanges(this);
            }
        }
        
        long TimeUntilWelfareAvailable = WelfareCooldownTimeRemaining(Player, CooldownSeconds);
        if (TimeUntilWelfareAvailable > 0)
        {
            StartCheckWelfareCooldownTimer();
        }
        
        UpdateWelfareState();
    }

    //Kicks off the check to see if cooldown has expired.
    protected void StartCheckWelfareCooldownTimer()
    {
        if (bCooldownExpireTimerActive)
        {
            return;
        }
        
        bCooldownExpireTimerActive = true;
        SendCustomEventDelayedSeconds(nameof(CheckWelfareCooldownExpired), 1.0f);
    }

    //Always call StartCheckWelfareCooldownTimer instead of this directly to make sure duplicate timers are not created.
    public void CheckWelfareCooldownExpired()
    {
        long WelfareTimeRemaining = WelfareCooldownTimeRemaining(Networking.LocalPlayer, CooldownSeconds);
        bCooldownExpireTimerActive = false;

        if (WelfareTimeRemaining > 0)
        {
            bCooldownExpireTimerActive = true;
            SendCustomEventDelayedSeconds(nameof(CheckWelfareCooldownExpired), 1);
            return;
        }
        
        UpdateWelfareState();
    }

    void UpdateWelfareState()
    {
        EWelfareStatus PreviousWelfareStatus = WelfareStatus;
        
        if (!bHasReceivedPlayerData)
        {
            WelfareStatus = EWelfareStatus.Locked;
        }
        else if (WelfareCooldownTimeRemaining(Networking.LocalPlayer, CooldownSeconds) > 0)
        {
            WelfareStatus = EWelfareStatus.Cooldown;
        }
        else if (IsPlayerBalanceAboveThreshold())
        {
            WelfareStatus = EWelfareStatus.Locked;
        }
        else
        {
            WelfareStatus = EWelfareStatus.Available;
        }

        if (WelfareStatus != PreviousWelfareStatus && ListenerComponentList != null)
        {
            for (int Index = ListenerComponentList.Length - 1; Index >= 0; Index--)
            {
                if (ListenerComponentList[Index])
                {
                    ListenerComponentList[Index].OnWelfareStatusChanged(this, WelfareStatus);
                }
            }
        }
    }

    bool IsPlayerBalanceAboveThreshold()
    {
        if (MaxBalanceThreshold <= 0)
        {
            return false;
        }

        PlayerBalanceComponent PlayerBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(Networking.LocalPlayer);
        if (!PlayerBalance || !PlayerBalance.IsBalanceReady())
        {
            return false;
        }

        return PlayerBalance.GetBalance() >= MaxBalanceThreshold;
    }

    public bool IsWelfareAvailable(VRC.SDKBase.VRCPlayerApi Player)
    {
        //NOTE: This flag is just a cached status value, we still need to check if cooldown expired.
        if (WelfareStatus != EWelfareStatus.Available)
        {
            return false;
        }

        if (WelfareCooldownTimeRemaining(Player, GetCooldownDuration()) > 0)
        {
            return false;
        }

        return true;
    }

    //Call this to attempt to redeem welfare.
    public virtual void RedeemWelfare(VRC.SDKBase.VRCPlayerApi Player)
    {
        if (!IsWelfareAvailable(Player))
        {
            return;
        }

        //Update that the welfare has been claimed before we grant it.
        UpdateWelfareClaimTime(this, Player);
        UpdateWelfareState();
        StartCheckWelfareCooldownTimer();
        
        GrantWelfare(Player);
        return;
    }

    protected virtual void GrantWelfare(VRC.SDKBase.VRCPlayerApi Player) {}
    
//==============
//Generic Helpers

    public const string WelfareClaimTimeKeyName = "HoldemWelfareLastClaim";

    public static long GetTimeNow()
    {
        return (DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond);
    }

    public static long TimeUntil(long Time)
    {
        return Time - GetTimeNow();
    }

    public static long TimeSince(long Time)
    {
        return GetTimeNow() - Time;
    }
    
    public static string TimeToString(long Time)
    {
        Time = Math.Max(Time, 0);
        
        long Minutes = Math.Min(Time / 60, 99);
        long Seconds = Time - (Time / 60) * 60; //We have to manually perform Time % 60 because udonsharp does not handle long % long.
        return $"{Minutes:D2}:{Seconds:D2}";
    }

    //NOTE: Will provide incorrect values if the player's persisted data is not available.
    public static long WelfareCooldownTimeRemaining(VRC.SDKBase.VRCPlayerApi Player, long Cooldown)
    {
        long WelfareClaimTime = 0;
        PlayerData.TryGetLong(Player, WelfareClaimTimeKeyName, out WelfareClaimTime);
        return Math.Max(TimeUntil(WelfareClaimTime + Cooldown), 0);
    }

    //NOTE: Will provide incorrect values if the player's persisted data is not available.
    public static long TimeSinceWelfareClaim(VRC.SDKBase.VRCPlayerApi Player)
    {
        long WelfareClaimTime = 0;
        PlayerData.TryGetLong(Player, WelfareClaimTimeKeyName, out WelfareClaimTime);
        return Math.Max(TimeSince(WelfareClaimTime), 0);
    }

    public static void UpdateWelfareClaimTime(WelfareComponent WelfareComponent, VRC.SDKBase.VRCPlayerApi Player)
    {
        if (!WelfareComponent || !WelfareComponent.HasReceivedPlayerData())
        {
            return;
        }
        
        if (Player == null || !Player.isLocal)
        {
            return;
        }
        
        PlayerData.SetLong(WelfareClaimTimeKeyName, GetTimeNow());
    }
    
    //Simple function to handle adding balances.
    //WelfareComponent is passed in so that anyone who calls this must validate initial persistence user data has been received.
    //Ideally the world creator creates a component that handles acknowledging persistence receipt centrally instead of having every component do it.
    public static void AddBalance(WelfareComponent WelfareComponent, VRC.SDKBase.VRCPlayerApi Player, int Delta)
    {
        PlayerBalanceComponent PlayerBalance = PlayerBalanceComponent.GetPlayerBalanceComponent(Player);
        if (PlayerBalance)
        {
            PlayerBalance.ModifyBalance(Delta);
        }
    }
}