using CMSMicroservice.Protobuf.Protos.Package;
using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;
using Severity = MudBlazor.Severity;

namespace FrontOffice.Main.Pages;

public partial class Checkout
{
    [Inject] private PackageService PackageService { get; set; } = default!;
    [Inject] private PackageContract.PackageContractClient PackageClient { get; set; } = default!;

    [Parameter] public long? PackageId { get; set; }

    private Pack? _selectedPackage;
    private bool _isProcessingPayment;

    // Discount code
    private string _discountCode = string.Empty;
    private bool _isApplyingDiscount;
    private string _discountMessage = string.Empty;
    private bool _discountApplied;
    private long _discountAmount;
    private long _finalPrice;

    private bool CanProceedToPayment => _selectedPackage != null;

    protected override async Task OnInitializedAsync()
    {
        await LoadPackageDetails();
    }

    private async Task LoadPackageDetails()
    {
        if (PackageId.HasValue)
        {
            try
            {
                var packages = await PackageService.GetAllPackagesAsync();
                var pkg = packages.FirstOrDefault(p => p.Id == PackageId.Value);
                if (pkg != null)
                {
                    _selectedPackage = new Pack(
                        Id: pkg.Id,
                        Title: pkg.Title,
                        Body: pkg.Description,
                        Image: pkg.ImageUrl,
                        Price: pkg.Price,
                        SupportsDirectPurchase: pkg.SupportsDirectPurchase,
                        SupportsDayaPurchase: pkg.SupportsDayaPurchase
                    );
                    _finalPrice = _selectedPackage.Price;
                }
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در بارگذاری پکیج: {ex.Message}", Severity.Error);
            }
        }
    }

    private async Task ApplyDiscountCode()
    {
        if (string.IsNullOrWhiteSpace(_discountCode))
        {
            _discountMessage = "لطفاً کد تخفیف را وارد کنید.";
            _discountApplied = false;
            return;
        }

        _isApplyingDiscount = true;
        _discountMessage = string.Empty;

        try
        {
            // TODO: Implement discount code validation with backend
            // For now, simulate a discount
            if (_discountCode.ToUpper() == "TEST10")
            {
                _discountAmount = (long)(_selectedPackage!.Price * 0.1); // 10% discount
                _finalPrice = _selectedPackage!.Price - _discountAmount;
                _discountMessage = "کد تخفیف با موفقیت اعمال شد.";
                _discountApplied = true;
            }
            else
            {
                _discountMessage = "کد تخفیف نامعتبر است.";
                _discountApplied = false;
                _discountAmount = 0;
                _finalPrice = _selectedPackage!.Price;
            }
        }
        catch (Exception)
        {
            _discountMessage = "خطا در اعمال کد تخفیف.";
            _discountApplied = false;
            _discountAmount = 0;
            _finalPrice = _selectedPackage!.Price;
        }
        finally
        {
            _isApplyingDiscount = false;
            await InvokeAsync(StateHasChanged);
        }
    }

    private async Task ProcessPayment()
    {
        if (_isProcessingPayment) return;

        if (!CanProceedToPayment || _selectedPackage == null)
        {
            Snackbar.Add("لطفاً پکیج را انتخاب کنید.", Severity.Warning);
            return;
        }

        _isProcessingPayment = true;

        try
        {
            var response = await PackageClient.CustomerPurchasePackageAsync(new CustomerPurchasePackageRequest
            {
                PackageId = _selectedPackage.Id,
                PurchaseMethod = PurchaseMethodEnum.PurchaseMethodGateway
            });

            if (!response.Success)
            {
                Snackbar.Add(response.Message ?? "خطا در آغاز فرآیند پرداخت", Severity.Error);
                return;
            }

            if (!string.IsNullOrEmpty(response.PaymentGatewayUrl))
            {
                Navigation.NavigateTo(response.PaymentGatewayUrl, forceLoad: true);
            }
            else
            {
                Snackbar.Add("خطا در دریافت آدرس درگاه پرداخت", Severity.Error);
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در پردازش پرداخت: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isProcessingPayment = false;
            await InvokeAsync(StateHasChanged);
        }
    }

    private async Task DayaLoanPayment()
    {
        if (_selectedPackage == null)
        {
            Snackbar.Add("لطفاً پکیج را انتخاب کنید.", Severity.Warning);
            return;
        }

        var url = "https://dayadiamond.ir/profile/creditpurchase/?merchantcode=56146364";
        await JSRuntime.InvokeVoidAsync("open", url, "_blank");
    }

    private record Pack(long Id, string Title, string Body, string Image, long Price, bool SupportsDirectPurchase = true, bool SupportsDayaPurchase = false);
}
