#nullable enable
using System;
using UnityEngine;
using IGP.Multiplayer.Models;
using IGP.UnitySDK;

namespace IGP.Multiplayer.Samples
{
    /// <summary>
    /// Minimal sample MonoBehaviour for a hosted game launched by the Curio desktop client.
    /// Attach this next to <see cref="IGPMultiplayerRuntime"/> to verify the multiplayer + achievement flow.
    /// </summary>
    public sealed class IGPHostedQuickstart : MonoBehaviour
    {
        [Header("References")]
        [SerializeField] private IGPRuntimeManager? coreRuntime = null;
        [SerializeField] private IGPMultiplayerRuntime? multiplayerRuntime = null;

        [Header("Sample Message")]
        [SerializeField] private string debugMessageType = "sample_debug";
        [SerializeField] private string debugText = "hello from igp-sdk";

        [Header("Achievement Sample")]
        [SerializeField] private string unlockAchievementKey = "first_session";
        [SerializeField] private string progressAchievementKey = "matches_played";
        [SerializeField] private double progressValue = 1d;
        [SerializeField] private string progressSourceKey = "sample_match_complete";

        [Header("Auto Actions")]
        [SerializeField] private bool initializeOnStart = true;
        [SerializeField] private bool setSceneGateOnRealtimeReady = true;
        [SerializeField] private string sceneGateValue = "arena-ready";

        private void Awake()
        {
            coreRuntime ??= FindObjectOfType<IGPRuntimeManager>();
            multiplayerRuntime ??= FindObjectOfType<IGPMultiplayerRuntime>();
        }

        private void OnEnable()
        {
            if (multiplayerRuntime == null)
            {
                Debug.LogWarning("[IGP Sample] IGPMultiplayerRuntime not found. Add it to the scene first.");
                return;
            }

            multiplayerRuntime.ConnectionChanged += HandleConnectionStateChanged;
            multiplayerRuntime.RoomChanged += HandleRoomChanged;
            multiplayerRuntime.MessageReceived += HandleMessageReceived;
            multiplayerRuntime.ErrorOccurred += HandleError;
        }

        private void OnDisable()
        {
            if (multiplayerRuntime == null)
            {
                return;
            }

            multiplayerRuntime.ConnectionChanged -= HandleConnectionStateChanged;
            multiplayerRuntime.RoomChanged -= HandleRoomChanged;
            multiplayerRuntime.MessageReceived -= HandleMessageReceived;
            multiplayerRuntime.ErrorOccurred -= HandleError;
        }

        private async void Start()
        {
            if (!initializeOnStart || coreRuntime == null)
            {
                return;
            }

            var initialized = await coreRuntime.InitializeAsync();
            if (!initialized)
            {
                Debug.LogError("[IGP Sample] SDK initialization failed.");
            }
        }

        public async void SendSampleMessage()
        {
            if (multiplayerRuntime == null)
            {
                Debug.LogWarning("[IGP Sample] multiplayerRuntime is missing.");
                return;
            }

            try
            {
                await multiplayerRuntime.SendMessageAsync(new Message
                {
                    type = debugMessageType,
                    roomId = multiplayerRuntime.CurrentRoomId,
                    playerId = multiplayerRuntime.PlayerId,
                    reliable = true,
                    content = new
                    {
                        text = debugText,
                        sentAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    }
                });

                Debug.Log($"[IGP Sample] Sent message `{debugMessageType}`.");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGP Sample] SendSampleMessage failed: {ex.Message}");
            }
        }

        public async void SetSceneGate()
        {
            if (multiplayerRuntime == null)
            {
                return;
            }

            try
            {
                await multiplayerRuntime.SetSceneGateAsync(sceneGateValue);
                Debug.Log($"[IGP Sample] Scene gate set to `{sceneGateValue}`.");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGP Sample] SetSceneGate failed: {ex.Message}");
            }
        }

        public async void UnlockSampleAchievement()
        {
            if (coreRuntime == null)
            {
                return;
            }

            try
            {
                var result = await IGPSDK.UnlockAchievementAsync(coreRuntime, unlockAchievementKey);
                Debug.Log($"[IGP Sample] UnlockAchievement success={result.success}, duplicated={result.duplicated}, message={result.message}");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGP Sample] UnlockSampleAchievement failed: {ex.Message}");
            }
        }

        public async void ReportSampleAchievementProgress()
        {
            if (coreRuntime == null)
            {
                return;
            }

            try
            {
                var result = await IGPSDK.ReportAchievementProgressAsync(
                    coreRuntime,
                    progressAchievementKey,
                    progressValue,
                    progressSourceKey);

                Debug.Log($"[IGP Sample] ReportAchievementProgress success={result.success}, duplicated={result.duplicated}, message={result.message}");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGP Sample] ReportSampleAchievementProgress failed: {ex.Message}");
            }
        }

        public async void SetGlobalSampleState()
        {
            if (multiplayerRuntime == null)
            {
                return;
            }

            try
            {
                await multiplayerRuntime.SetGlobalStateAsync("sample:lastMessageAt", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
                Debug.Log("[IGP Sample] Updated global sample state.");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGP Sample] SetGlobalSampleState failed: {ex.Message}");
            }
        }

        public async void CallSampleRpc()
        {
            if (multiplayerRuntime == null)
            {
                return;
            }

            try
            {
                var requestId = await multiplayerRuntime.CallRPCAsync(
                    "sample_echo",
                    new
                    {
                        text = debugText,
                        sentAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    });

                Debug.Log($"[IGP Sample] RPC dispatched with requestId={requestId}");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGP Sample] CallSampleRpc failed: {ex.Message}");
            }
        }

        private void HandleRoomChanged(IGPRoomChangedEvent change)
        {
            if (change.Kind == IGPRoomChangeKind.Joined && change.Room != null)
            {
                Debug.Log($"[IGP Sample] Joined room id={change.Room.id}, code={change.Room.code}, host={change.Room.hostId}");
            }
        }

        private async void HandleConnectionStateChanged(IGPMultiplayerConnectionChangedEvent change)
        {
            Debug.Log($"[IGP Sample] Connection changed: state={change.State}, ready={change.IsReady}");

            if (!change.IsReady ||
                !setSceneGateOnRealtimeReady ||
                multiplayerRuntime == null ||
                !string.Equals(multiplayerRuntime.CurrentRoomData.hostId, multiplayerRuntime.PlayerId, StringComparison.Ordinal))
            {
                return;
            }

            try
            {
                await multiplayerRuntime.SetSceneGateAsync(sceneGateValue);
                Debug.Log($"[IGP Sample] Scene gate set to `{sceneGateValue}` after realtime connected.");
            }
            catch (Exception ex)
            {
                Debug.LogError($"[IGP Sample] Automatic scene gate update failed: {ex.Message}");
            }
        }

        private void HandleMessageReceived(IGPMessageReceivedEvent message)
        {
            var payloadJson = message.Content != null ? Newtonsoft.Json.JsonConvert.SerializeObject(message.Content) : "<null>";
            Debug.Log($"[IGP Sample] Message received type={message.MessageType}, payload={payloadJson}");
        }

        private void HandleError(IGPMultiplayerErrorEvent error)
        {
            Debug.LogError($"[IGP Sample] Runtime error: {error}");
        }
    }
}
