using System.Collections.Generic;
using CrazyGames;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;

public class RoomScene : MonoBehaviourPunCallbacks
{
    public TMP_Text statsText;
    public TMP_Text roomNameText;

    private void Start()
    {
        roomNameText.text = $"Room: {PhotonNetwork.CurrentRoom.Name}";
        UpdateStats();
        UpdateCrazyGamesRoom();

        if (PhotonNetwork.InRoom)
        {
            SpawnPlayer();
        }
    }

    public override void OnJoinedRoom()
    {
        SpawnPlayer();
    }

    private void SpawnPlayer()
    {
        Vector3 spawnPos = new Vector3(Random.Range(-3f, 3f), 0, Random.Range(-3f, 3f));
        PhotonNetwork.Instantiate("PlayerPrefab", spawnPos, Quaternion.identity);
    }

    public void OnLeaveClick()
    {
        Logger.Log("Leaving room...");
        PhotonNetwork.LeaveRoom();
    }

    public override void OnLeftRoom()
    {
        CrazySDK.Game.LeftRoom();
        SceneManager.LoadScene("Lobby");
    }

    public override void OnPlayerEnteredRoom(Player newPlayer)
    {
        UpdateStats();
        UpdateCrazyGamesRoom();
    }

    public override void OnPlayerLeftRoom(Player otherPlayer)
    {
        UpdateStats();
        UpdateCrazyGamesRoom();
    }

    private void UpdateStats()
    {
        string hostStatus = PhotonNetwork.IsMasterClient ? "Host" : "Client";
        statsText.text = $"Players: {PhotonNetwork.CurrentRoom.PlayerCount} ({hostStatus})";
    }

    private void UpdateCrazyGamesRoom()
    {
        var room = PhotonNetwork.CurrentRoom;

        // you can add additional logic here:
        // perhaps only the host should be able to invite friends (mark the room as joinable), or do you want everyone in room to be able to invite?
        // maybe the room should be joinable only in the initial phase before the match starts?
        var isJoinable = room.IsOpen && room.PlayerCount < room.MaxPlayers;

        var updateRoomInput = new UpdateRoomInput()
        {
            // the room ID allows us to identify friends that are playing in the same room as you
            // so ensure it uniquely identifies the room, even across regions
            RoomId = room.Name + PhotonNetwork.NetworkingClient.CloudRegion,
            IsJoinable = isJoinable,
        };

        if (isJoinable)
        {
            updateRoomInput.InviteParams = new Dictionary<string, string>()
            {
                { "regionId", PhotonNetwork.NetworkingClient.CloudRegion },
                { "roomName", room.Name },
            };
        }

        Logger.Log("Updating CrazyGames room with: " + updateRoomInput);
        CrazySDK.Game.UpdateRoom(updateRoomInput);
    }
}
