@* Merged into /system *@
@attribute [Authorize]

@using CMSMicroservice.Protobuf.Protos.Health
@using Google.Protobuf.WellKnownTypes
@using MudBlazor
@inject HealthContract.HealthContractClient HealthClient

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

    <!-- Overall System Status -->
    <MudCard Class="mb-4" Elevation="3">
        <MudCardContent>
            <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center">
                <MudStack Spacing="2">
                    <MudText Typo="Typo.h5">وضعیت کلی سیستم</MudText>
                    <MudText Typo="Typo.body2" Color="Color.Secondary">
                        آخرین بروزرسانی: @_lastUpdated.ToString("HH:mm:ss")
                    </MudText>
                </MudStack>
                <MudChip T="string" 
                         Size="Size.Large" 
                         Color="@(_overallStatus == "Healthy" ? Color.Success : Color.Error)"
                         Icon="@(_overallStatus == "Healthy" ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Error)">
                    @(_overallStatus == "Healthy" ? "سالم" : "مشکل‌دار")
                </MudChip>
            </MudStack>
        </MudCardContent>
    </MudCard>

    <!-- Services Health -->
    <MudText Typo="Typo.h6" Class="mb-3">وضعیت سرویس‌ها</MudText>
    <MudGrid Class="mb-4">
        @foreach (var service in _services)
        {
            <MudItem xs="12" md="6" lg="3">
                <MudCard Elevation="2">
                    <MudCardContent>
                        <MudStack Spacing="2">
                            <MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center">
                                <MudText Typo="Typo.h6">@service.Name</MudText>
                                <MudIcon Icon="@GetServiceIcon(service.Type)" 
                                         Color="@GetHealthColor(service.Status)" 
                                         Size="Size.Large" />
                            </MudStack>

                            <MudChip T="string" 
                                     Size="Size.Small" 
                                     Color="@GetHealthColor(service.Status)">
                                @GetHealthText(service.Status)
                            </MudChip>

                            <MudDivider />

                            <MudStack Spacing="1">
                                <MudStack Row="true" Justify="Justify.SpaceBetween">
                                    <MudText Typo="Typo.caption" Color="Color.Secondary">Uptime:</MudText>
                                    <MudText Typo="Typo.caption"><strong>@service.Uptime</strong></MudText>
                                </MudStack>
                                <MudStack Row="true" Justify="Justify.SpaceBetween">
                                    <MudText Typo="Typo.caption" Color="Color.Secondary">زمان پاسخ:</MudText>
                                    <MudText Typo="Typo.caption"><strong>@service.ResponseTime ms</strong></MudText>
                                </MudStack>
                                <MudStack Row="true" Justify="Justify.SpaceBetween">
                                    <MudText Typo="Typo.caption" Color="Color.Secondary">نسخه:</MudText>
                                    <MudText Typo="Typo.caption"><strong>@service.Version</strong></MudText>
                                </MudStack>
                            </MudStack>

                            @if (!string.IsNullOrEmpty(service.LastError))
                            {
                                <MudAlert Severity="Severity.Error" Dense="true" Class="mt-2">
                                    @service.LastError
                                </MudAlert>
                            }
                        </MudStack>
                    </MudCardContent>
                    <MudCardActions>
                        <MudButton Size="Size.Small" 
                                   Color="Color.Primary" 
                                   OnClick="@(() => CheckServiceHealth(service))">
                            بررسی
                        </MudButton>
                        <MudButton Size="Size.Small" 
                                   Color="Color.Secondary" 
                                   OnClick="@(() => ViewServiceLogs(service))">
                            لاگ‌ها
                        </MudButton>
                    </MudCardActions>
                </MudCard>
            </MudItem>
        }
    </MudGrid>

    <!-- System Resources -->
    <MudText Typo="Typo.h6" Class="mb-3">منابع سیستم</MudText>
    <MudCard Class="mb-4">
        <MudCardContent Class="d-flex flex-column align-center justify-center" Style="min-height: 120px;">
            <MudIcon Icon="@Icons.Material.Filled.MonitorHeart" Size="Size.Large" Color="Color.Secondary" Class="mb-2" />
            <MudText Typo="Typo.body1" Color="Color.Secondary">
                مانیتورینگ منابع سیستم (CPU، حافظه، دیسک، شبکه) در نسخه‌های آینده با اتصال به Prometheus/Grafana فعال خواهد شد.
            </MudText>
        </MudCardContent>
    </MudCard>

    <!-- Recent Events -->
    <MudText Typo="Typo.h6" Class="mb-3">رویدادهای اخیر سیستم</MudText>
    <MudCard>
        <MudCardContent>
            <MudTimeline TimelineOrientation="TimelineOrientation.Vertical">
                @foreach (var evt in _recentEvents)
                {
                    <MudTimelineItem Color="@GetEventColor(evt.Type)" Size="Size.Small">
                        <ItemOpposite>
                            <MudText Typo="Typo.caption" Color="Color.Secondary">
                                @evt.Timestamp.ToString("HH:mm:ss")
                            </MudText>
                        </ItemOpposite>
                        <ItemContent>
                            <MudStack Spacing="0">
                                <MudText Typo="Typo.body2"><strong>@evt.Message</strong></MudText>
                                <MudText Typo="Typo.caption" Color="Color.Secondary">@evt.Source</MudText>
                            </MudStack>
                        </ItemContent>
                    </MudTimelineItem>
                }
            </MudTimeline>
        </MudCardContent>
    </MudCard>
</div>

@code {
    private string _overallStatus = "Healthy";
    private DateTime _lastUpdated = DateTime.Now;
    private List<ServiceHealth> _services = new();

    private List<SystemEvent> _recentEvents = new();

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

    private async Task LoadHealthData()
    {
        try
        {
            // CMS proto uses google.protobuf.Empty instead of GetSystemHealthRequest
            var response = await HealthClient.GetSystemHealthAsync(new Empty());
            
            _overallStatus = response.OverallHealthy ? "Healthy" : "Unhealthy";
            _lastUpdated = DateTime.Now;
            
            // Map gRPC services to UI model
            _services = response.Services.Select(s => new ServiceHealth
            {
                Name = s.ServiceName,
                Type = GetServiceType(s.ServiceName),
                Status = s.Status.ToString(),
                Uptime = "99.9%", // Mock - not in API
                ResponseTime = (int)s.ResponseTimeMs,
                Version = "1.0.0", // Mock - not in API
                LastError = s.Status != HealthStatus.Healthy ? s.Description : null
            }).ToList();
            
            // Keep mock events for now
            _recentEvents = GenerateMockEvents();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری اطلاعات: {ex.Message}", Severity.Error);
            // Fallback to mock data
            _services = GenerateMockServices();
            _recentEvents = GenerateMockEvents();
        }
    }

    private async Task CheckServiceHealth(ServiceHealth service)
    {
        try
        {
            Snackbar.Add($"در حال بررسی {service.Name}...", Severity.Info);
            await Task.Delay(1000);
            
            // Refresh health check for this specific service
            await LoadHealthData();
            service = _services.FirstOrDefault(s => s.Name == service.Name) ?? service;
            
            Snackbar.Add($"{service.Name} سالم است", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا: {ex.Message}", Severity.Error);
        }
    }

    private void ViewServiceLogs(ServiceHealth service)
    {
        // Future enhancement: Open logs dialog showing service execution history
        Snackbar.Add($"نمایش لاگ‌های {service.Name}", Severity.Info);
    }

    private Color GetHealthColor(string status)
    {
        return status switch
        {
            "Healthy" => Color.Success,
            "Degraded" => Color.Warning,
            "Unhealthy" => Color.Error,
            _ => Color.Default
        };
    }

    private string GetHealthText(string status)
    {
        return status switch
        {
            "Healthy" => "سالم",
            "Degraded" => "کاهش عملکرد",
            "Unhealthy" => "ناسالم",
            _ => "نامشخص"
        };
    }

    private Color GetEventColor(string type)
    {
        return type switch
        {
            "Info" => Color.Info,
            "Warning" => Color.Warning,
            "Error" => Color.Error,
            "Success" => Color.Success,
            _ => Color.Default
        };
    }

    private string GetServiceIcon(string type)
    {
        return type switch
        {
            "API" => Icons.Material.Filled.Api,
            "Database" => Icons.Material.Filled.Storage,
            "Cache" => Icons.Material.Filled.Memory,
            "Queue" => Icons.Material.Filled.Queue,
            _ => Icons.Material.Filled.Cloud
        };
    }

    private string GetServiceType(string serviceName)
    {
        if (serviceName.Contains("Commission") || serviceName.Contains("Configuration")) return "API";
        if (serviceName.Contains("Network") || serviceName.Contains("Club")) return "API";
        if (serviceName.Contains("Database") || serviceName.Contains("SQL")) return "Database";
        if (serviceName.Contains("Redis") || serviceName.Contains("Cache")) return "Cache";
        return "API";
    }

    private List<ServiceHealth> GenerateMockServices()
    {
        return new List<ServiceHealth>
        {
            new() { 
                Name = "CMS API", 
                Type = "API",
                Status = "Healthy", 
                Uptime = "99.98%", 
                ResponseTime = 85,
                Version = "1.2.3"
            },
            new() { 
                Name = "BFF API", 
                Type = "API",
                Status = "Healthy", 
                Uptime = "99.95%", 
                ResponseTime = 62,
                Version = "1.1.0"
            },
            new() { 
                Name = "PostgreSQL", 
                Type = "Database",
                Status = "Healthy", 
                Uptime = "99.99%", 
                ResponseTime = 12,
                Version = "15.3"
            },
            new() { 
                Name = "Redis Cache", 
                Type = "Cache",
                Status = "Degraded", 
                Uptime = "98.50%", 
                ResponseTime = 245,
                Version = "7.0",
                LastError = "زمان پاسخ بالاتر از حد معمول"
            },
            new() { 
                Name = "RabbitMQ", 
                Type = "Queue",
                Status = "Healthy", 
                Uptime = "99.92%", 
                ResponseTime = 35,
                Version = "3.12"
            },
            new() { 
                Name = "Email Service", 
                Type = "API",
                Status = "Healthy", 
                Uptime = "99.80%", 
                ResponseTime = 156,
                Version = "1.0.5"
            }
        };
    }

    private List<SystemEvent> GenerateMockEvents()
    {
        var now = DateTime.Now;
        return new List<SystemEvent>
        {
            new() { 
                Timestamp = now.AddMinutes(-2), 
                Type = "Success",
                Message = "محاسبه کمیسیون هفتگی با موفقیت انجام شد",
                Source = "Commission Worker"
            },
            new() { 
                Timestamp = now.AddMinutes(-5), 
                Type = "Info",
                Message = "پشتیبان‌گیری خودکار پایگاه داده آغاز شد",
                Source = "Database Service"
            },
            new() { 
                Timestamp = now.AddMinutes(-12), 
                Type = "Warning",
                Message = "Redis Cache زمان پاسخ بالای 200ms",
                Source = "Health Monitor"
            },
            new() { 
                Timestamp = now.AddMinutes(-18), 
                Type = "Info",
                Message = "سرویس BFF API راه‌اندازی مجدد شد",
                Source = "System"
            },
            new() { 
                Timestamp = now.AddMinutes(-25), 
                Type = "Success",
                Message = "10 درخواست برداشت پردازش شد",
                Source = "Payment Service"
            }
        };
    }

    private class ServiceHealth
    {
        public string Name { get; set; } = "";
        public string Type { get; set; } = "";
        public string Status { get; set; } = "";
        public string Uptime { get; set; } = "";
        public int ResponseTime { get; set; }
        public string Version { get; set; } = "";
        public string? LastError { get; set; }
    }

    private class SystemEvent
    {
        public DateTime Timestamp { get; set; }
        public string Type { get; set; } = "";
        public string Message { get; set; } = "";
        public string Source { get; set; } = "";
    }
}
