@page "/system/alerts"
@attribute [Authorize]

@using MudBlazor

<div>
    <MudText Typo="Typo.h4" GutterBottom="true">مدیریت هشدارها</MudText>
    <MudText Typo="Typo.body1" Color="Color.Secondary" Class="mb-4">
        مشاهده و مدیریت هشدارهای سیستم
    </MudText>

    <!-- Summary Cards -->
    <MudGrid Class="mb-4">
        <MudItem xs="12" md="3">
            <MudCard Elevation="2">
                <MudCardContent>
                    <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center">
                        <MudStack Spacing="1">
                            <MudText Typo="Typo.body2" Color="Color.Secondary">کل هشدارها</MudText>
                            <MudText Typo="Typo.h5">@_totalAlerts</MudText>
                        </MudStack>
                        <MudIcon Icon="@Icons.Material.Filled.NotificationsActive" Size="Size.Large" Color="Color.Default" />
                    </MudStack>
                </MudCardContent>
            </MudCard>
        </MudItem>

        <MudItem xs="12" md="3">
            <MudCard Elevation="2">
                <MudCardContent>
                    <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center">
                        <MudStack Spacing="1">
                            <MudText Typo="Typo.body2" Color="Color.Secondary">بحرانی</MudText>
                            <MudText Typo="Typo.h5" Color="Color.Error">@_criticalAlerts</MudText>
                        </MudStack>
                        <MudIcon Icon="@Icons.Material.Filled.Error" Size="Size.Large" Color="Color.Error" />
                    </MudStack>
                </MudCardContent>
            </MudCard>
        </MudItem>

        <MudItem xs="12" md="3">
            <MudCard Elevation="2">
                <MudCardContent>
                    <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center">
                        <MudStack Spacing="1">
                            <MudText Typo="Typo.body2" Color="Color.Secondary">هشدار</MudText>
                            <MudText Typo="Typo.h5" Color="Color.Warning">@_warningAlerts</MudText>
                        </MudStack>
                        <MudIcon Icon="@Icons.Material.Filled.Warning" Size="Size.Large" Color="Color.Warning" />
                    </MudStack>
                </MudCardContent>
            </MudCard>
        </MudItem>

        <MudItem xs="12" md="3">
            <MudCard Elevation="2">
                <MudCardContent>
                    <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center">
                        <MudStack Spacing="1">
                            <MudText Typo="Typo.body2" Color="Color.Secondary">حل شده امروز</MudText>
                            <MudText Typo="Typo.h5" Color="Color.Success">@_resolvedToday</MudText>
                        </MudStack>
                        <MudIcon Icon="@Icons.Material.Filled.CheckCircle" Size="Size.Large" Color="Color.Success" />
                    </MudStack>
                </MudCardContent>
            </MudCard>
        </MudItem>
    </MudGrid>

    <!-- Filters -->
    <MudCard Class="mb-4">
        <MudCardContent>
            <MudGrid>
                <MudItem xs="12" md="3">
                    <MudSelect @bind-Value="_filterSeverity" 
                               Label="سطح هشدار" 
                               Variant="Variant.Outlined"
                               Margin="Margin.Dense">
                        <MudSelectItem T="string?" Value="@((string?)null)">همه</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Critical")">بحرانی</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Warning")">هشدار</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Info")">اطلاعات</MudSelectItem>
                    </MudSelect>
                </MudItem>

                <MudItem xs="12" md="3">
                    <MudSelect @bind-Value="_filterStatus" 
                               Label="وضعیت" 
                               Variant="Variant.Outlined"
                               Margin="Margin.Dense">
                        <MudSelectItem T="string?" Value="@((string?)null)">همه</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Active")">فعال</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Resolved")">حل شده</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Acknowledged")">تایید شده</MudSelectItem>
                    </MudSelect>
                </MudItem>

                <MudItem xs="12" md="3">
                    <MudSelect @bind-Value="_filterSource" 
                               Label="منبع" 
                               Variant="Variant.Outlined"
                               Margin="Margin.Dense">
                        <MudSelectItem T="string?" Value="@((string?)null)">همه</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Commission")">کمیسیون</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Network")">شبکه</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("Club")">باشگاه</MudSelectItem>
                        <MudSelectItem T="string?" Value="@("System")">سیستم</MudSelectItem>
                    </MudSelect>
                </MudItem>

                <MudItem xs="12" md="3" Class="d-flex align-center">
                    <MudButton Variant="Variant.Filled" 
                               Color="Color.Primary" 
                               OnClick="ApplyFilters"
                               StartIcon="@Icons.Material.Filled.FilterList"
                               FullWidth="true">
                        اعمال فیلتر
                    </MudButton>
                </MudItem>
            </MudGrid>
        </MudCardContent>
    </MudCard>

    <!-- Alerts Table -->
    <MudCard>
        <MudCardContent>
            @if (_loading)
            {
                <MudProgressCircular Color="Color.Primary" Indeterminate="true" />
            }
            else
            {
                <MudTable Items="@_filteredAlerts" 
                          Hover="true" 
                          Breakpoint="Breakpoint.Sm"
                          Dense="true"
                          Striped="true">
                    <HeaderContent>
                        <MudTh>سطح</MudTh>
                        <MudTh>عنوان</MudTh>
                        <MudTh>منبع</MudTh>
                        <MudTh>توضیحات</MudTh>
                        <MudTh>زمان</MudTh>
                        <MudTh>وضعیت</MudTh>
                        <MudTh>عملیات</MudTh>
                    </HeaderContent>
                    <RowTemplate>
                        <MudTd DataLabel="سطح">
                            <MudChip T="string" 
                                     Size="Size.Small" 
                                     Color="@GetSeverityColor(context.Severity)">
                                @GetSeverityText(context.Severity)
                            </MudChip>
                        </MudTd>
                        <MudTd DataLabel="عنوان">
                            <MudText Typo="Typo.body2"><strong>@context.Title</strong></MudText>
                        </MudTd>
                        <MudTd DataLabel="منبع">
                            <MudChip T="string" Size="Size.Small" Variant="Variant.Outlined">
                                @context.Source
                            </MudChip>
                        </MudTd>
                        <MudTd DataLabel="توضیحات">
                            <MudText Typo="Typo.body2" Style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                @context.Description
                            </MudText>
                        </MudTd>
                        <MudTd DataLabel="زمان">
                            <MudText Typo="Typo.caption">@context.CreatedAt.MiladiToJalaliWithTime()</MudText>
                        </MudTd>
                        <MudTd DataLabel="وضعیت">
                            <MudChip T="string" 
                                     Size="Size.Small" 
                                     Color="@GetStatusColor(context.Status)">
                                @GetStatusText(context.Status)
                            </MudChip>
                        </MudTd>
                        <MudTd DataLabel="عملیات">
                            <MudStack Row="true" Spacing="1">
                                <MudIconButton Icon="@Icons.Material.Filled.Visibility" 
                                               Size="Size.Small" 
                                               Color="Color.Info"
                                               OnClick="@(() => ViewDetails(context))" />
                                @if (context.Status == "Active")
                                {
                                    <MudIconButton Icon="@Icons.Material.Filled.Check" 
                                                   Size="Size.Small" 
                                                   Color="Color.Success"
                                                   OnClick="@(() => AcknowledgeAlert(context))" />
                                    <MudIconButton Icon="@Icons.Material.Filled.Close" 
                                                   Size="Size.Small" 
                                                   Color="Color.Warning"
                                                   OnClick="@(() => ResolveAlert(context))" />
                                }
                            </MudStack>
                        </MudTd>
                    </RowTemplate>
                    <PagerContent>
                        <MudTablePager PageSizeOptions="new int[]{10, 25, 50, 100}" />
                    </PagerContent>
                </MudTable>
            }
        </MudCardContent>
    </MudCard>
</div>

@code {
    private bool _loading = false;
    private List<AlertModel> _alerts = new();
    private List<AlertModel> _filteredAlerts = new();

    // Statistics
    private int _totalAlerts = 0;
    private int _criticalAlerts = 0;
    private int _warningAlerts = 0;
    private int _resolvedToday = 0;

    // Filters
    private string? _filterSeverity;
    private string? _filterStatus;
    private string? _filterSource;

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

    private async Task LoadAlerts()
    {
        _loading = true;
        try
        {
            // NOTE: This page uses mock data. Requires AlertLog table in CMS microservice.
            // Future API: AlertClient.GetAllAlertsAsync() with filtering support
            await Task.Delay(500); // Simulate API call
            _alerts = GenerateMockAlerts();
            _filteredAlerts = _alerts;
            CalculateStatistics();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری هشدارها: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private async Task ApplyFilters()
    {
        _filteredAlerts = _alerts
            .Where(a => string.IsNullOrEmpty(_filterSeverity) || a.Severity == _filterSeverity)
            .Where(a => string.IsNullOrEmpty(_filterStatus) || a.Status == _filterStatus)
            .Where(a => string.IsNullOrEmpty(_filterSource) || a.Source == _filterSource)
            .ToList();

        await Task.CompletedTask;
    }

    private void CalculateStatistics()
    {
        _totalAlerts = _alerts.Count;
        _criticalAlerts = _alerts.Count(a => a.Severity == "Critical");
        _warningAlerts = _alerts.Count(a => a.Severity == "Warning");
        _resolvedToday = _alerts.Count(a => a.Status == "Resolved" && a.ResolvedAt?.Date == DateTime.Today);
    }

    private Color GetSeverityColor(string severity)
    {
        return severity switch
        {
            "Critical" => Color.Error,
            "Warning" => Color.Warning,
            "Info" => Color.Info,
            _ => Color.Default
        };
    }

    private string GetSeverityText(string severity)
    {
        return severity switch
        {
            "Critical" => "بحرانی",
            "Warning" => "هشدار",
            "Info" => "اطلاعات",
            _ => "نامشخص"
        };
    }

    private Color GetStatusColor(string status)
    {
        return status switch
        {
            "Active" => Color.Error,
            "Acknowledged" => Color.Warning,
            "Resolved" => Color.Success,
            _ => Color.Default
        };
    }

    private string GetStatusText(string status)
    {
        return status switch
        {
            "Active" => "فعال",
            "Acknowledged" => "تایید شده",
            "Resolved" => "حل شده",
            _ => "نامشخص"
        };
    }

    private void ViewDetails(AlertModel alert)
    {
        // Future enhancement: Open dialog with full alert details, stack traces, related logs
        Snackbar.Add($"جزئیات هشدار: {alert.Title}", Severity.Info);
    }

    private async Task AcknowledgeAlert(AlertModel alert)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "تایید هشدار",
            $"آیا از تایید این هشدار مطمئن هستید؟\n\n{alert.Title}",
            yesText: "بله", cancelText: "خیر");

        if (confirmed == true)
        {
            try
            {
                // Future API: AlertClient.AcknowledgeAlertAsync(alert.Id)
                alert.Status = "Acknowledged";
                Snackbar.Add("هشدار تایید شد", Severity.Success);
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
            }
        }
    }

    private async Task ResolveAlert(AlertModel alert)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "حل هشدار",
            $"آیا این هشدار حل شده است؟\n\n{alert.Title}",
            yesText: "بله، حل شد", cancelText: "خیر");

        if (confirmed == true)
        {
            try
            {
                // Future API: AlertClient.ResolveAlertAsync(alert.Id)
                alert.Status = "Resolved";
                alert.ResolvedAt = DateTime.Now;
                CalculateStatistics();
                Snackbar.Add("هشدار به عنوان حل شده علامت‌گذاری شد", Severity.Success);
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
            }
        }
    }

    private List<AlertModel> GenerateMockAlerts()
    {
        var random = new Random();
        var severities = new[] { "Critical", "Warning", "Info" };
        var statuses = new[] { "Active", "Acknowledged", "Resolved" };
        var sources = new[] { "Commission", "Network", "Club", "System" };
        var titles = new[]
        {
            "خطا در محاسبه کمیسیون هفتگی",
            "تعداد درخواست‌های برداشت بیش از حد معمول",
            "Worker کمیسیون متوقف شده",
            "پایگاه داده بالای 80% ظرفیت",
            "تعداد کاربران فعال کاهش یافته",
            "خطا در ارسال ایمیل",
            "زمان پاسخ سرور بیش از حد معمول",
            "عضو باشگاه منقضی شده نیاز به تمدید",
            "موجودی کیف پول اصلی کم است",
            "سرویس پرداخت در دسترس نیست"
        };

        var alerts = new List<AlertModel>();
        for (int i = 0; i < 25; i++)
        {
            var createdAt = DateTime.Now.AddHours(-random.Next(0, 72));
            var status = statuses[random.Next(statuses.Length)];
            
            alerts.Add(new AlertModel
            {
                Id = i + 1,
                Severity = severities[random.Next(severities.Length)],
                Title = titles[random.Next(titles.Length)],
                Description = "توضیحات تکمیلی در مورد این هشدار. این متن برای نمایش جزئیات بیشتر در مورد مشکل یا وضعیتی که رخ داده است.",
                Source = sources[random.Next(sources.Length)],
                Status = status,
                CreatedAt = createdAt,
                AcknowledgedAt = status != "Active" ? createdAt.AddMinutes(random.Next(5, 60)) : null,
                ResolvedAt = status == "Resolved" ? createdAt.AddHours(random.Next(1, 24)) : null
            });
        }

        return alerts.OrderByDescending(a => a.CreatedAt).ToList();
    }

    private class AlertModel
    {
        public int Id { get; set; }
        public string Severity { get; set; } = "";
        public string Title { get; set; } = "";
        public string Description { get; set; } = "";
        public string Source { get; set; } = "";
        public string Status { get; set; } = "";
        public DateTime CreatedAt { get; set; }
        public DateTime? AcknowledgedAt { get; set; }
        public DateTime? ResolvedAt { get; set; }
    }
}
