
using System;
using UdonSharp;
using UdonSharp.Localization;
using UnityEngine;
using VRC.SDK3.UdonNetworkCalling;
using VRC.SDKBase;
using VRC.Udon;
using VRC.Udon.Common.Interfaces;
using Random = UnityEngine.Random;

public enum EWheelState
{
    None,
    Spinning,
    Bouncing
}

[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
public class WheelWelfareComponent : WelfareComponent
{
    [SerializeField]
    private float MinInitialSpeed = 160.0f;

    [SerializeField]
    private float MaxInitialSpeed = 240.0f;

    [SerializeField]
    private float Deceleration = 10.0f;

    [SerializeField]
    private float SnapThreshold = 1.0f;

    [SerializeField]
    private float BounceDamping = 0.25f;

    private WheelWelfareTileComponent[] TileComponentList = null;
    private float CurrentSpeed = 0f;
    
    private float BounceAngleLimit = 0f;
    private int WinningTileIndex = -1;
    private int HighlightedTileIndex = -1;
    private VRCPlayerApi SpinPlayer = null;
    private int SpinPlayerID = -1;
    
    [UdonSynced]
    private EWheelState WheelState = EWheelState.None;
    [UdonSynced]
    private float AuthorityCurrentRotation = 0.0f;
    [UdonSynced]
    private float AuthorityCurrentRotationRate = 0.0f;

    private float LocalCurrentRotation = 0.0f;
    private float LastRotationSendTime = 0.0f;

    public override void Start()
    {
        base.Start();
        
        TileComponentList = GetComponentsInChildren<WheelWelfareTileComponent>();

        for (int Index = 0; Index < TileComponentList.Length; Index++)
        {
            TileComponentList[Index].RegisterWheel(this);
        }

        if (Networking.IsOwner(gameObject))
        {
            AuthorityCurrentRotation = gameObject.transform.localEulerAngles.x;
            AuthorityCurrentRotationRate = 0.0f;
            RequestSerialization();
        }
    }

    //Called by a player instigator to spin the wheel.
    [NetworkCallable]
    public void RequestSpin(int RequesterPlayerID)
    {
        VRCPlayerApi RequesterPlayer = VRCPlayerApi.GetPlayerById(RequesterPlayerID);
        
        if (WheelState != EWheelState.None)
        {
            return;
        }
        
        //Let everyone (including the requester) know that a player has spun the wheel.
        SendCustomNetworkEvent(NetworkEventTarget.All, nameof(NotifyPlayerSpin), RequesterPlayer.playerId);
    }

    //Called by the wheel owner to notify players (and the spinning player) a spin was instigated.
    [NetworkCallable]
    public void NotifyPlayerSpin(int SpinnerPlayerID)
    {
        SpinPlayerID = SpinnerPlayerID;
        SpinPlayer = VRCPlayerApi.GetPlayerById(SpinnerPlayerID);

        if (SpinPlayer.isLocal)
        {
            UpdateWelfareClaimTime(this, SpinPlayer);
        }

        if (!Networking.IsOwner(gameObject))
        {
            return;
        }

        GrantWelfare(SpinPlayer);
        RequestSerialization();
    }

    public override void RedeemWelfare(VRCPlayerApi Player)
    {
        if (!IsWelfareAvailable(Player))
        {
            return;
        }

        if (!Player.isLocal || WheelState != EWheelState.None)
        {
            return;
        }
        
        SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(RequestSpin), Player.playerId);
    }

    protected override void GrantWelfare(VRCPlayerApi Player)
    {
        CurrentSpeed = Random.Range(MinInitialSpeed, MaxInitialSpeed);
        LocalCurrentRotation = Mathf.Repeat(LocalCurrentRotation, 360.0f);
        AuthorityCurrentRotation = LocalCurrentRotation;
        AuthorityCurrentRotationRate = CurrentSpeed;

        if (HighlightedTileIndex >= 0 && HighlightedTileIndex < TileComponentList.Length)
        {
            TileComponentList[HighlightedTileIndex].OnHighlightStateChange(false);
            HighlightedTileIndex = -1;
        }

        WheelState = EWheelState.Spinning;
        RequestSerialization();
    }

    public override void OnDeserialization()
    {
        if (!Networking.IsOwner(gameObject))
        {
            CurrentSpeed = AuthorityCurrentRotationRate;
        }
    }

    public void Update()
    {
        // Note: WelfareComponent no longer polls in Update()
        // Welfare state updates are now event-driven via OnPlayerDataUpdated
        // This Update() is only for wheel spinning animation

        if (WheelState == EWheelState.Spinning)
        {
            Spin();
        }
        else if (WheelState == EWheelState.Bouncing)
        {
            Bounce();
        }
    }

    protected void Spin()
    {
        if (Networking.IsOwner(gameObject))
        {
            LocalCurrentRotation += CurrentSpeed * Time.deltaTime;
            AuthorityCurrentRotation = LocalCurrentRotation;
        }
        else
        {
            float AngleDiff = AuthorityCurrentRotation - LocalCurrentRotation;
            float SpeedModifier = 1.0f;
            
            if (Math.Abs(AngleDiff) > 20.0f)
            {
                LocalCurrentRotation = AuthorityCurrentRotation;
                CurrentSpeed = AuthorityCurrentRotationRate;
            }
            else if (AngleDiff > 4.0f)
            {
                SpeedModifier = 0.9f;
            }
            else if (AngleDiff < -4.0f)
            {
                SpeedModifier = 1.1f;
            }
            
            AuthorityCurrentRotation += CurrentSpeed * Time.deltaTime;
            LocalCurrentRotation += CurrentSpeed * Time.deltaTime * SpeedModifier;
        }

        Vector3 NewRotation = Vector3.zero;
        NewRotation.x = LocalCurrentRotation;
        transform.localEulerAngles = NewRotation;
        
        CurrentSpeed -= Deceleration * Time.deltaTime;

        if (Networking.IsOwner(gameObject))
        {
            AuthorityCurrentRotationRate = CurrentSpeed;
            LastRotationSendTime += Time.deltaTime;
            if (LastRotationSendTime > 0.5f)
            {
                LastRotationSendTime = 0.0f;
                RequestSerialization();
            }
        }
        
        UpdateHighlight();
        
        if (CurrentSpeed > SnapThreshold)
        {
            return;
        }

        WinningTileIndex = GetWinningTileIndex();
        BeginBounce(WinningTileIndex);
    }

    protected void Bounce()
    {
        CurrentSpeed = Mathf.MoveTowards(CurrentSpeed, 0f, Deceleration * Time.deltaTime);

        transform.Rotate(CurrentSpeed * Time.deltaTime, 0f, 0f, Space.Self);

        Vector3 SpinAxis = transform.right;
        Vector3 ReferenceDirection = -Vector3.up;

        Vector3 TileProjected = Vector3.ProjectOnPlane(TileComponentList[WinningTileIndex].transform.forward, SpinAxis).normalized;
        Vector3 ReferenceProjected = Vector3.ProjectOnPlane(ReferenceDirection, SpinAxis).normalized;

        float AngleFromCenter = Vector3.Angle(TileProjected, ReferenceProjected);

        if (AngleFromCenter > BounceAngleLimit)
        {
            float SignedAngle = Vector3.SignedAngle(TileProjected, ReferenceProjected, SpinAxis);
            float Overshoot = AngleFromCenter - BounceAngleLimit;

            transform.Rotate(Mathf.Sign(SignedAngle) * Overshoot, 0f, 0f, Space.Self);

            CurrentSpeed = -CurrentSpeed * BounceDamping;
        }

        if (Mathf.Abs(CurrentSpeed) > 0.01f)
        {
            return;
        }

        FinishSpinning();
    }

    private void FinishSpinning()
    {
        WheelState = EWheelState.None;
        RequestSerialization();

        if (SpinPlayer != null && SpinPlayer.isLocal && TileComponentList != null && WinningTileIndex >= 0 && WinningTileIndex < TileComponentList.Length)
        {
            TileComponentList[WinningTileIndex].GrantTileEffect(SpinPlayer);
        }
    }

    private void UpdateHighlight()
    {
        int CurrentIndex = GetWinningTileIndex();

        if (CurrentIndex == HighlightedTileIndex) return;

        if (HighlightedTileIndex >= 0 && HighlightedTileIndex < TileComponentList.Length)
        {
            TileComponentList[HighlightedTileIndex].OnHighlightStateChange(false);
        }

        HighlightedTileIndex = CurrentIndex;

        if (HighlightedTileIndex >= 0 && HighlightedTileIndex < TileComponentList.Length)
        {
            TileComponentList[HighlightedTileIndex].OnHighlightStateChange(true);
        }
    }

    private int GetWinningTileIndex()
    {
        if (TileComponentList == null || TileComponentList.Length == 0)
        {
            return 0;
        }
        
        Vector3 ReferenceDirection = -Vector3.up;
        int BestIndex = 0;
        float BestDot = -2.0f;

        for (int Index = 0; Index < TileComponentList.Length; Index++)
        {
            float Dot = Vector3.Dot(TileComponentList[Index].transform.forward, ReferenceDirection);
            if (Dot > BestDot)
            {
                BestDot = Dot;
                BestIndex = Index;
            }
        }

        return BestIndex;
    }

    private void BeginBounce(int TileIndex)
    {
        if (TileComponentList.Length <= 1)
        {
            FinishSpinning();
            return;
        }
        
        Vector3 SpinAxis = transform.right;
        Vector3 WinningForward = Vector3.ProjectOnPlane(TileComponentList[TileIndex].transform.forward, SpinAxis).normalized;

        float SmallestAngle = 360f;
        for (int Index = 0; Index < TileComponentList.Length; Index++)
        {
            if (Index == TileIndex) continue;
            Vector3 TileForward = Vector3.ProjectOnPlane(TileComponentList[Index].transform.forward, SpinAxis).normalized;
            float Angle = Vector3.Angle(WinningForward, TileForward);
            if (Angle < SmallestAngle) SmallestAngle = Angle;
        }

        BounceAngleLimit = SmallestAngle / 2f;
        
        WheelState = EWheelState.Bouncing;
    }
}
