@page "/settings/app-versions"
@attribute [Authorize]

@using BackOffice.Services.AppVersion
@using BackOffice.Pages.Settings.Components
@inject IAppVersionService AppVersionService
@inject IDialogService DialogService
@inject ISnackbar Snackbar

<PageTitle>مدیریت نسخه اپلیکیشن‌ها</PageTitle>

<div>
    <MudText Typo="Typo.h4" GutterBottom="true">
        <MudIcon Icon="@Icons.Material.Filled.PhoneAndroid" Class="ml-2" />
        مدیریت نسخه اپلیکیشن‌ها
    </MudText>
    <MudText Typo="Typo.body1" Color="Color.Secondary" Class="mb-4">
        مدیریت نسخه‌های اپلیکیشن‌های موبایل و کنترل به‌روزرسانی اجباری
    </MudText>
    
    <MudPaper Class="pa-4">
        <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center" Class="mb-4">
            <MudSwitch Value="_includeInactive" 
                       Color="Color.Primary" 
                       Label="نمایش نسخه‌های غیرفعال"
                       T="bool"
                       ValueChanged="@(async (bool val) => { _includeInactive = val; await LoadVersions(); })" />
            
            <MudStack Row="true" Spacing="2">
                <MudButton Variant="Variant.Filled" 
                           Color="Color.Primary" 
                           StartIcon="@Icons.Material.Filled.Add"
                           OnClick="@OpenCreateDialog">
                    افزودن نسخه جدید
                </MudButton>
                <MudButton Variant="Variant.Outlined" 
                           Color="Color.Primary" 
                           StartIcon="@Icons.Material.Filled.Refresh"
                           OnClick="@LoadVersions">
                    بارگذاری مجدد
                </MudButton>
            </MudStack>
        </MudStack>
        
        @if (_loading)
        {
            <MudProgressLinear Color="Color.Primary" Indeterminate="true" Class="mb-4" />
        }

        <MudDataGrid T="AppVersionDto" 
                     Items="@_versions" 
                     Loading="@_loading"
                     Hover="true"
                     Dense="true">
            <Columns>
                <PropertyColumn Property="x => x.Id" Title="شناسه" />
                
                <TemplateColumn Title="اپلیکیشن">
                    <CellTemplate>
                        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="2">
                            <MudIcon Icon="@GetAppIcon(context.Item.AppName)" 
                                     Color="@GetAppColor(context.Item.AppName)" 
                                     Size="Size.Small" />
                            <MudText>@context.Item.AppNameDisplay</MudText>
                        </MudStack>
                    </CellTemplate>
                </TemplateColumn>
                
                <TemplateColumn Title="نسخه فعلی">
                    <CellTemplate>
                        <MudChip T="string" Color="Color.Primary" Size="Size.Small" Variant="Variant.Outlined">
                            @context.Item.CurrentVersion
                        </MudChip>
                    </CellTemplate>
                </TemplateColumn>
                
                <TemplateColumn Title="حداقل نسخه">
                    <CellTemplate>
                        @if (!string.IsNullOrEmpty(context.Item.MinRequiredVersion))
                        {
                            <MudChip T="string" Color="Color.Warning" Size="Size.Small" Variant="Variant.Outlined">
                                @context.Item.MinRequiredVersion
                            </MudChip>
                        }
                        else
                        {
                            <MudText Typo="Typo.body2" Color="Color.Default">-</MudText>
                        }
                    </CellTemplate>
                </TemplateColumn>
                
                <TemplateColumn Title="پاکسازی کش">
                    <CellTemplate>
                        @if (context.Item.RequiresFullCacheClear)
                        {
                            <MudIcon Icon="@Icons.Material.Filled.Warning" Color="Color.Warning" Size="Size.Small" />
                        }
                        else
                        {
                            <MudIcon Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success" Size="Size.Small" />
                        }
                    </CellTemplate>
                </TemplateColumn>
                
                <TemplateColumn Title="وضعیت">
                    <CellTemplate>
                        @if (context.Item.IsActive)
                        {
                            <MudChip T="string" Color="Color.Success" Size="Size.Small">فعال</MudChip>
                        }
                        else
                        {
                            <MudChip T="string" Color="Color.Default" Size="Size.Small">غیرفعال</MudChip>
                        }
                    </CellTemplate>
                </TemplateColumn>
                
                <TemplateColumn Title="آخرین تغییر">
                    <CellTemplate>
                        @(context.Item.LastModified?.MiladiToJalaliWithTime() ?? "—")
                    </CellTemplate>
                </TemplateColumn>
                
                <TemplateColumn Title="عملیات" Sortable="false">
                    <CellTemplate>
                        <MudIconButton Icon="@Icons.Material.Filled.Edit" 
                                       Color="Color.Primary" 
                                       Size="Size.Small"
                                       OnClick="@(() => OpenEditDialog(context.Item))" />
                        <MudIconButton Icon="@Icons.Material.Filled.Visibility" 
                                       Color="Color.Info" 
                                       Size="Size.Small"
                                       OnClick="@(() => OpenDetailsDialog(context.Item))" />
                    </CellTemplate>
                </TemplateColumn>
            </Columns>
            <NoRecordsContent>
                <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="my-4">موردی یافت نشد.</MudAlert>
            </NoRecordsContent>
        </MudDataGrid>
    </MudPaper>
    
    @* Info Cards *@
    <MudGrid Class="mt-4">
        @foreach (var version in _versions.Where(v => v.IsActive))
        {
            <MudItem xs="12" md="6">
                <MudCard Elevation="2">
                    <MudCardHeader>
                        <CardHeaderAvatar>
                            <MudAvatar Color="@GetAppColor(version.AppName)">
                                <MudIcon Icon="@GetAppIcon(version.AppName)" />
                            </MudAvatar>
                        </CardHeaderAvatar>
                        <CardHeaderContent>
                            <MudText Typo="Typo.h6">@version.AppNameDisplay</MudText>
                            <MudText Typo="Typo.body2" Color="Color.Secondary">@version.AppName</MudText>
                        </CardHeaderContent>
                        <CardHeaderActions>
                            <MudIconButton Icon="@Icons.Material.Filled.Edit" 
                                           Color="Color.Primary"
                                           OnClick="@(() => OpenEditDialog(version))" />
                        </CardHeaderActions>
                    </MudCardHeader>
                    <MudCardContent>
                        <MudStack Spacing="2">
                            <MudStack Row="true" Justify="Justify.SpaceBetween">
                                <MudText Typo="Typo.body2">نسخه فعلی:</MudText>
                                <MudChip T="string" Color="Color.Primary" Size="Size.Small">@version.CurrentVersion</MudChip>
                            </MudStack>
                            
                            <MudStack Row="true" Justify="Justify.SpaceBetween">
                                <MudText Typo="Typo.body2">حداقل نسخه:</MudText>
                                @if (!string.IsNullOrEmpty(version.MinRequiredVersion))
                                {
                                    <MudChip T="string" Color="Color.Warning" Size="Size.Small">@version.MinRequiredVersion</MudChip>
                                }
                                else
                                {
                                    <MudText Typo="Typo.body2" Color="Color.Default">تنظیم نشده</MudText>
                                }
                            </MudStack>
                            
                            @if (version.RequiresFullCacheClear)
                            {
                                <MudAlert Severity="Severity.Warning" Dense="true" Class="mt-2">
                                    نیاز به پاکسازی کامل کش دارد
                                </MudAlert>
                            }
                            
                            @if (!string.IsNullOrEmpty(version.UpdateMessage))
                            {
                                <MudDivider Class="my-2" />
                                <MudText Typo="Typo.caption" Color="Color.Secondary">پیام به‌روزرسانی:</MudText>
                                <MudText Typo="Typo.body2">@version.UpdateMessage</MudText>
                            }
                        </MudStack>
                    </MudCardContent>
                </MudCard>
            </MudItem>
        }
    </MudGrid>
</div>

@code {
    private List<AppVersionDto> _versions = new();
    private bool _loading = false;
    private bool _includeInactive = false;

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

    private async Task LoadVersions()
    {
        _loading = true;
        try
        {
            _versions = await AppVersionService.GetAllAsync(_includeInactive);
            Snackbar.Add("اطلاعات نسخه‌ها بارگذاری شد", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private async Task OpenCreateDialog()
    {
        var parameters = new DialogParameters<AppVersionEditDialog>
        {
            { x => x.Model, new UpdateAppVersionDto
                {
                    AppName = "",
                    CurrentVersion = "1.0.0",
                    MinRequiredVersion = null,
                    RequiresFullCacheClear = false,
                    UpdateMessage = null,
                    ReleaseNotes = null
                }
            },
            { x => x.IsNew, true }
        };

        var options = new DialogOptions
        {
            CloseButton = true,
            MaxWidth = MaxWidth.Medium,
            FullWidth = true
        };

        var dialog = await DialogService.ShowAsync<AppVersionEditDialog>(
            "افزودن نسخه جدید",
            parameters,
            options);

        var result = await dialog.Result;

        if (result is { Canceled: false, Data: UpdateAppVersionDto dto })
        {
            try
            {
                await AppVersionService.UpdateAsync(dto);
                Snackbar.Add("نسخه جدید با موفقیت ایجاد شد", Severity.Success);
                await LoadVersions();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در ایجاد: {ex.Message}", Severity.Error);
            }
        }
    }

    private async Task OpenEditDialog(AppVersionDto version)
    {
        var parameters = new DialogParameters<AppVersionEditDialog>
        {
            { x => x.Model, new UpdateAppVersionDto
                {
                    AppName = version.AppName,
                    CurrentVersion = version.CurrentVersion,
                    MinRequiredVersion = version.MinRequiredVersion,
                    RequiresFullCacheClear = version.RequiresFullCacheClear,
                    UpdateMessage = version.UpdateMessage,
                    ReleaseNotes = version.ReleaseNotes
                }
            }
        };

        var options = new DialogOptions
        {
            CloseButton = true,
            MaxWidth = MaxWidth.Medium,
            FullWidth = true
        };

        var dialog = await DialogService.ShowAsync<AppVersionEditDialog>(
            $"ویرایش نسخه {version.AppNameDisplay}",
            parameters,
            options);

        var result = await dialog.Result;

        if (result is { Canceled: false, Data: UpdateAppVersionDto dto })
        {
            try
            {
                await AppVersionService.UpdateAsync(dto);
                Snackbar.Add("نسخه با موفقیت به‌روزرسانی شد", Severity.Success);
                await LoadVersions();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در به‌روزرسانی: {ex.Message}", Severity.Error);
            }
        }
    }

    private void OpenDetailsDialog(AppVersionDto version)
    {
        var parameters = new DialogParameters
        {
            { "ContentText", BuildDetailsContent(version) },
            { "ButtonText", "بستن" },
            { "Color", Color.Primary }
        };

        DialogService.Show<MudMessageBox>($"جزئیات {version.AppNameDisplay}", parameters);
    }

    private string BuildDetailsContent(AppVersionDto version)
    {
        var lines = new List<string>
        {
            $"نام اپلیکیشن: {version.AppName}",
            $"نسخه فعلی: {version.CurrentVersion}",
            $"حداقل نسخه: {version.MinRequiredVersion ?? "تنظیم نشده"}",
            $"نیاز به پاکسازی کش: {(version.RequiresFullCacheClear ? "بله" : "خیر")}",
            $"وضعیت: {(version.IsActive ? "فعال" : "غیرفعال")}",
            "",
            "پیام به‌روزرسانی:",
            version.UpdateMessage ?? "ندارد",
            "",
            "یادداشت‌های انتشار:",
            version.ReleaseNotes ?? "ندارد",
            "",
            $"تاریخ ایجاد: {version.Created?.MiladiToJalaliWithTime() ?? "-"}",
            $"آخرین تغییر: {version.LastModified?.MiladiToJalaliWithTime() ?? "-"}"
        };
        return string.Join(Environment.NewLine, lines);
    }

    private string GetAppIcon(string appName) => appName switch
    {
        "KaraBazarApp" => Icons.Material.Filled.ShoppingCart,
        "KaraBazarAdminApp" => Icons.Material.Filled.AdminPanelSettings,
        _ => Icons.Material.Filled.PhoneAndroid
    };

    private Color GetAppColor(string appName) => appName switch
    {
        "KaraBazarApp" => Color.Primary,
        "KaraBazarAdminApp" => Color.Secondary,
        _ => Color.Default
    };
}
