using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using UnityEngine;

namespace FRVR
{
    public class IAPModule : MonoBehaviour
    {
        private FRVRSDK _frvrSDK;
        
    // Callback storage for IL2CPP compatibility
    private Action<string> _purchaseCallback;
    private Action<string> _consumePurchaseCallback;
    private Action<string> _getUnconsumedPurchasesCallback;
    private Action<string> _restorePurchasesCallback;

        public void Init(FRVRSDK frvrSDK)
        {
            _frvrSDK = frvrSDK;
        }

    public bool IsReady()
    {
        if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
        {
            return false;
        }

        return _frvrSDK.WrapSDKFunc(
            () => IapIsReadySDK(),
            () => true // Editor simulation
        );
    }

    public string GetCatalog()
    {
        if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
        {
            return "{}";
        }

        return _frvrSDK.WrapSDKFunc(
            () => IapGetCatalogSDK(),
            () => "{\"products\":[]}" // Editor simulation
        );
    }

    public string GetProduct(string productId)
    {
        if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
        {
            return "{}";
        }

        _frvrSDK.DebugLog($"Getting product: {productId}");

        return _frvrSDK.WrapSDKFunc(
            () => IapGetProductSDK(productId),
            () => "{\"id\":\"" + productId + "\",\"price\":\"$0.99\"}" // Editor simulation
        );
    }

    public string GetProductPrice(string productId)
    {
        string productJson = GetProduct(productId);
        
        if (string.IsNullOrEmpty(productJson) || productJson == "{}")
        {
            return string.Empty;
        }

        // Extract price field from JSON string using regex
        var match = Regex.Match(productJson, @"""price""\s*:\s*""([^""]+)""");
        if (match.Success && match.Groups.Count > 1)
        {
            return match.Groups[1].Value;
        }

        return string.Empty;
    }

    public void Purchase(string productId, Action<string> callback, string metaJson = null)
    {
        if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
        {
            return;
        }

        _frvrSDK.DebugLog($"Purchasing product: {productId}");

        _purchaseCallback = callback;

        _frvrSDK.WrapSDKAction(
            () =>
            {
                IapPurchaseSDK(productId, metaJson);
            },
            () =>
            {
                // Editor simulation
                _frvrSDK.DebugLog("Editor: Simulating purchase success");
                callback("{\"productId\":\"" + productId + "\",\"purchaseId\":\"testPurchaseId\"}");
            }
        );
    }

    public void ConsumePurchase(string purchaseJson, Action<string> callback)
    {
        if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
        {
            return;
        }

        _frvrSDK.DebugLog($"Consuming purchase: {purchaseJson}");

        _consumePurchaseCallback = callback;

        _frvrSDK.WrapSDKAction(
            () =>
            {
                IapConsumePurchaseSDK(purchaseJson);
            },
            () =>
            {
                // Editor simulation
                _frvrSDK.DebugLog("Editor: Simulating consume purchase success");
                callback("testPurchaseId");
            }
        );
    }

    public void GetUnconsumedPurchases(Action<string> callback)
    {
        if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
        {
            return;
        }

        _frvrSDK.DebugLog("Getting unconsumed purchases");

        _getUnconsumedPurchasesCallback = callback;

        _frvrSDK.WrapSDKAction(
            () =>
            {
                IapGetUnconsumedPurchasesSDK();
            },
            () =>
            {
                // Editor simulation
                _frvrSDK.DebugLog("Editor: Simulating get unconsumed purchases");
                callback("[]");
            }
        );
    }

    public void RestorePurchases(Action<string> callback)
    {
        if (!Application.isEditor && Application.platform != RuntimePlatform.WebGLPlayer)
        {
            return;
        }

        _frvrSDK.DebugLog("Restoring purchases");

        _restorePurchasesCallback = callback;

        _frvrSDK.WrapSDKAction(
            () =>
            {
                IapRestorePurchasesSDK();
            },
            () =>
            {
                // Editor simulation
                _frvrSDK.DebugLog("Editor: Simulating restore purchases");
                callback("[]");
            }
        );
    }

    // JSLib callback methods
        internal void HandleIapPurchaseComplete(string result)
        {
            _purchaseCallback?.Invoke(result);
        }

        internal void HandleIapConsumePurchaseComplete(string purchaseId)
        {
            _consumePurchaseCallback?.Invoke(purchaseId);
        }

    internal void HandleIapGetUnconsumedPurchasesComplete(string purchasesJson)
    {
        _getUnconsumedPurchasesCallback?.Invoke(purchasesJson);
    }

    internal void HandleIapRestorePurchasesComplete(string purchasesJson)
    {
        _restorePurchasesCallback?.Invoke(purchasesJson);
    }

#if UNITY_WEBGL
        [DllImport("__Internal")]
        private static extern bool IapIsReadySDK();
        
        [DllImport("__Internal")]
        private static extern string IapGetCatalogSDK();
        
        [DllImport("__Internal")]
        private static extern string IapGetProductSDK(string productId);
        
        [DllImport("__Internal")]
        private static extern void IapPurchaseSDK(string productId, string metaJson);
        
        [DllImport("__Internal")]
        private static extern void IapConsumePurchaseSDK(string purchaseJsonString);
        
    [DllImport("__Internal")]
    private static extern void IapGetUnconsumedPurchasesSDK();
    
    [DllImport("__Internal")]
    private static extern void IapRestorePurchasesSDK();
#else
    private bool IapIsReadySDK() { return false; }
    private string IapGetCatalogSDK() { return "{}"; }
    private string IapGetProductSDK(string productId) { return "{}"; }
    private void IapPurchaseSDK(string productId, string metaJson) { }
    private void IapConsumePurchaseSDK(string purchaseJsonString) { }
    private void IapGetUnconsumedPurchasesSDK() { }
    private void IapRestorePurchasesSDK() { }
#endif
    }
}
