@using FrontOffice.Main.Utilities
@inject PackageService PackageService
@inject ISnackbar Snackbar

<MudDialog>
    <TitleContent>
        @if (_selectedPackage != null)
        {
            <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                <MudIconButton Icon="@Icons.Material.Filled.ArrowForward"
                               Size="Size.Small"
                               OnClick="BackToList" />
                <MudText Typo="Typo.h6">انتخاب روش پرداخت</MudText>
            </MudStack>
        }
        else
        {
            <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                <MudIcon Icon="@Icons.Material.Filled.ShoppingCart" Color="Color.Primary" />
                <MudText Typo="Typo.h6">انتخاب پکیج</MudText>
            </MudStack>
        }
    </TitleContent>
    <DialogContent>
        @if (_isLoading)
        {
            <MudStack AlignItems="AlignItems.Center" Class="py-8">
                <MudProgressCircular Color="Color.Primary" Indeterminate="true" />
                <MudText Typo="Typo.body2" Class="mud-text-secondary mt-2">در حال بارگذاری پکیج‌ها...</MudText>
            </MudStack>
        }
        else if (_selectedPackage != null)
        {
            @* ── Step 2: Payment method selection ── *@
            <MudStack Spacing="3">
                @* Selected Package Summary *@
                <MudPaper Elevation="0" Class="pa-3 rounded-lg" Style="background:rgba(99,102,241,.06);">
                    <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                        <MudAvatar Size="Size.Medium" Style="background:rgba(99,102,241,.15); color:#6366f1;">
                            <MudIcon Icon="@Icons.Material.Filled.Inventory2" />
                        </MudAvatar>
                        <MudStack Spacing="0" Class="flex-grow-1">
                            <MudText Typo="Typo.subtitle1"><b>@_selectedPackage.Title</b></MudText>
                            <MudText Typo="Typo.body2" Color="Color.Success">@_selectedPackage.FormattedPrice</MudText>
                        </MudStack>
                    </MudStack>
                </MudPaper>

                <MudDivider />

                <MudText Typo="Typo.body2" Class="mud-text-secondary">
                    روش پرداخت خود را انتخاب کنید:
                </MudText>

                @* Direct Payment — always available *@
                <MudPaper Elevation="0" Class="pa-4 rounded-lg pkg-payment-option"
                          Style="border:2px solid var(--mud-palette-primary); cursor:pointer;"
                          @onclick="() => SelectPaymentMethod(PaymentMethodType.DirectPayment)">
                    <MudStack Spacing="2">
                        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                            <MudIcon Icon="@Icons.Material.Filled.CreditCard" Color="Color.Primary" Size="Size.Medium" />
                            <MudStack Spacing="0" Class="flex-grow-1">
                                <MudText Typo="Typo.subtitle1" Color="Color.Primary"><b>پرداخت مستقیم</b></MudText>
                                <MudText Typo="Typo.caption" Class="mud-text-secondary">پرداخت آنی از طریق درگاه بانکی</MudText>
                            </MudStack>
                            <MudIcon Icon="@Icons.Material.Filled.ArrowBack" Color="Color.Primary" Size="Size.Small" />
                        </MudStack>
                    </MudStack>
                </MudPaper>

                @* Daya Loan — only for base package AND first purchase cycle *@
                @if (_selectedPackage.SupportsDayaPurchase && PurchaseCycleCount == 0)
                {
                    <MudPaper Elevation="0" Class="pa-4 rounded-lg pkg-payment-option"
                              Style="border:2px solid var(--mud-palette-tertiary); cursor:pointer;"
                              @onclick="() => SelectPaymentMethod(PaymentMethodType.DayaLoan)">
                        <MudStack Spacing="2">
                            <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                                <MudIcon Icon="@Icons.Material.Filled.Diamond" Color="Color.Tertiary" Size="Size.Medium" />
                                <MudStack Spacing="0" Class="flex-grow-1">
                                    <MudText Typo="Typo.subtitle1" Color="Color.Tertiary"><b>اعتبار الماسی دایا</b></MudText>
                                    <MudText Typo="Typo.caption" Class="mud-text-secondary">تأمین اعتبار از طریق خرید توکن الماس</MudText>
                                </MudStack>
                                <MudIcon Icon="@Icons.Material.Filled.ArrowBack" Color="Color.Tertiary" Size="Size.Small" />
                            </MudStack>
                        </MudStack>
                    </MudPaper>
                }
                else if (!_selectedPackage.SupportsDayaPurchase)
                {
                    <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="mt-1">
                        اعتبار الماسی دایا فقط برای پکیج پایه قابل استفاده است.
                    </MudAlert>
                }
                else if (PurchaseCycleCount > 0)
                {
                    <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="mt-1">
                        از دور دوم به بعد، خرید پکیج فقط از طریق درگاه بانکی امکان‌پذیر است.
                    </MudAlert>
                }
            </MudStack>
        }
        else
        {
            @* ── Step 1: Package tile grid ── *@
            <MudStack Spacing="3">
                <MudText Typo="Typo.body2" Class="mud-text-secondary">
                    پکیج مورد نظر خود را انتخاب کنید:
                </MudText>

                <MudGrid Spacing="3">
                    @foreach (var pkg in _packages)
                    {
                        <MudItem xs="12" sm="6" md="@(_packages.Count <= 2 ? 6 : 4)">
                            <MudPaper Elevation="0" Class="pa-4 rounded-xl pkg-tile text-center"
                                      Style="@GetTileStyle(pkg)"
                                      @onclick="() => SelectPackage(pkg)">
                                @if (pkg.IsBasePackage)
                                {
                                    <MudChip T="string" Size="Size.Small" Color="Color.Primary" Variant="Variant.Filled"
                                             Class="pkg-tile-badge">پایه</MudChip>
                                }
                                <MudStack Spacing="1" AlignItems="AlignItems.Center">
                                    <MudAvatar Size="Size.Large" Style="@GetAvatarStyle(pkg)" Class="mb-1">
                                        <MudIcon Icon="@Icons.Material.Filled.Inventory2" Size="Size.Large" />
                                    </MudAvatar>
                                    <MudText Typo="Typo.subtitle1"><b>@pkg.Title</b></MudText>
                                    <MudText Typo="Typo.h6" Color="Color.Success">@pkg.FormattedPrice</MudText>
                                    @if (!string.IsNullOrWhiteSpace(pkg.Description))
                                    {
                                        <MudText Typo="Typo.caption" Class="mud-text-secondary"
                                                 Style="display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">
                                            @((MarkupString)pkg.Description)
                                        </MudText>
                                    }
                                    @* Key features *@
                                    <MudStack Spacing="0" Class="mt-2" Style="width:100%;">
                                        @if (pkg.MagicWalletMultiplier > 0)
                                        {
                                            <MudText Typo="Typo.caption" Class="mud-text-secondary">
                                                <MudIcon Icon="@Icons.Material.Filled.AutoAwesome" Size="Size.Small" Class="me-1" Style="font-size:.85rem;vertical-align:middle;" />
                                                ضریب جادویی: @pkg.MagicWalletMultiplier.ToString("F1")x
                                            </MudText>
                                        }
                                        @if (pkg.DiscountMultiplier > 0)
                                        {
                                            <MudText Typo="Typo.caption" Class="mud-text-secondary">
                                                <MudIcon Icon="@Icons.Material.Filled.Discount" Size="Size.Small" Class="me-1" Style="font-size:.85rem;vertical-align:middle;" />
                                                ضریب اعتبار: @pkg.DiscountMultiplier.ToString("F1")x
                                            </MudText>
                                        }
                                        @if (pkg.SupportsDayaPurchase)
                                        {
                                            <MudText Typo="Typo.caption" Color="Color.Tertiary">
                                                <MudIcon Icon="@Icons.Material.Filled.Diamond" Size="Size.Small" Class="me-1" Style="font-size:.85rem;vertical-align:middle;" />
                                                قابل خرید با دایا
                                            </MudText>
                                        }
                                    </MudStack>
                                </MudStack>
                            </MudPaper>
                        </MudItem>
                    }
                </MudGrid>
            </MudStack>
        }
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel" Variant="Variant.Text" Color="Color.Default">بستن</MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] private IMudDialogInstance MudDialog { get; set; } = default!;

    /// <summary>Number of previous purchase cycles — controls Daya eligibility</summary>
    [Parameter] public int PurchaseCycleCount { get; set; }

    private List<PackageDto> _packages = new();
    private PackageDto? _selectedPackage;
    private bool _isLoading = true;

    protected override async Task OnInitializedAsync()
    {
        _isLoading = true;
        try
        {
            _packages = await PackageService.GetAllPackagesAsync();
        }
        catch (Exception ex)
        {
            Snackbar.Add("خطا در بارگذاری پکیج‌ها", MudBlazor.Severity.Error);
        }
        finally
        {
            _isLoading = false;
        }
    }

    private void SelectPackage(PackageDto package)
    {
        _selectedPackage = package;
    }

    private void BackToList()
    {
        _selectedPackage = null;
    }

    private void SelectPaymentMethod(PaymentMethodType method)
    {
        var result = new PackagePurchaseResult(_selectedPackage!, method);
        MudDialog.Close(DialogResult.Ok(result));
    }

    private void Cancel() => MudDialog.Cancel();

    private static string GetTileStyle(PackageDto pkg)
    {
        return pkg.IsBasePackage
            ? "border:2px solid var(--mud-palette-primary); background:rgba(99,102,241,.04); cursor:pointer;"
            : "border:2px solid var(--mud-palette-lines-default); background:var(--mud-palette-surface); cursor:pointer;";
    }

    private static string GetAvatarStyle(PackageDto pkg)
    {
        return pkg.IsBasePackage
            ? "background:rgba(99,102,241,.15); color:#6366f1;"
            : "background:rgba(16,185,129,.12); color:#10b981;";
    }

    public enum PaymentMethodType { DirectPayment, DayaLoan }
    public record PackagePurchaseResult(PackageDto Package, PaymentMethodType Method);
}
