@* Merged into /system *@

@using MudBlazor
@using BackOffice.Pages.SystemManagement
@using BackOffice.Pages.AutoComplete

<div>
    <MudText Typo="Typo.h4" GutterBottom="true">کنترل Worker محاسبات</MudText>
    <MudText Typo="Typo.body1" Color="Color.Secondary" Class="mb-4">
        مدیریت و نظارت بر Worker محاسبات هفتگی کمیسیون
    </MudText>

    <MudGrid>
        <!-- Worker Status -->
        <MudItem xs="12" md="6">
            <MudCard Elevation="2">
                <MudCardHeader>
                    <MudText Typo="Typo.h6">وضعیت Worker</MudText>
                </MudCardHeader>
                <MudCardContent>
                    <MudSimpleTable Dense="true">
                        <tbody>
                            <tr>
                                <td><strong>وضعیت:</strong></td>
                                <td>
                                    <MudChip T="string" 
                                             Color="@(_workerStatus == WorkerStatus.Running ? Color.Success : Color.Error)" 
                                             Size="Size.Small">
                                        @GetWorkerStatusText()
                                    </MudChip>
                                </td>
                            </tr>
                            <tr>
                                <td><strong>آخرین اجرا:</strong></td>
                                <td>@PersianDateTime.ConvertToPersianDateTime(_lastRunTime)</td>
                            </tr>
                            <tr>
                                <td><strong>اجرای بعدی:</strong></td>
                                <td>@PersianDateTime.ConvertToPersianDateTime(_nextRunTime)</td>
                            </tr>
                            <tr>
                                <td><strong>تعداد اجراهای موفق:</strong></td>
                                <td><MudChip T="string" Color="Color.Success" Size="Size.Small">@_successfulRuns</MudChip></td>
                            </tr>
                            <tr>
                                <td><strong>تعداد خطاها:</strong></td>
                                <td><MudChip T="string" Color="Color.Error" Size="Size.Small">@_failedRuns</MudChip></td>
                            </tr>
                        </tbody>
                    </MudSimpleTable>
                </MudCardContent>
            </MudCard>
        </MudItem>

        <!-- Control Panel -->
        <MudItem xs="12" md="6">
            <MudCard Elevation="2">
                <MudCardHeader>
                    <MudText Typo="Typo.h6">پنل کنترل</MudText>
                </MudCardHeader>
                <MudCardContent>
                    <MudStack Spacing="3">
                        <WeekNumberPicker Label="شماره هفته برای اجرای دستی" 
                                         @bind-SelectedWeekDefinitionId="_manualWeekDefinitionId"
                                         @* @bind-SelectedWeekNumber="_manualWeekDisplayName" *@
                                         CoerceText="true" />
                        
                        <MudButton Variant="Variant.Filled" 
                                   Color="Color.Primary" 
                                   FullWidth="true"
                                   StartIcon="@Icons.Material.Filled.PlayArrow"
                                   OnClick="RunManualCalculation"
                                   Disabled="@_isProcessing">
                            اجرای دستی محاسبات
                        </MudButton>

                        <MudDivider />

                        @if (_workerStatus == WorkerStatus.Running)
                        {
                            <MudButton Variant="Variant.Filled" 
                                       Color="Color.Warning" 
                                       FullWidth="true"
                                       StartIcon="@Icons.Material.Filled.Pause"
                                       OnClick="PauseWorker"
                                       Disabled="@_isProcessing">
                                توقف موقت Worker
                            </MudButton>
                        }
                        else if (_workerStatus == WorkerStatus.Paused)
                        {
                            <MudButton Variant="Variant.Filled" 
                                       Color="Color.Success" 
                                       FullWidth="true"
                                       StartIcon="@Icons.Material.Filled.PlayArrow"
                                       OnClick="ResumeWorker"
                                       Disabled="@_isProcessing">
                                ازسرگیری Worker
                            </MudButton>
                        }

                        <MudButton Variant="Variant.Outlined" 
                                   Color="Color.Info" 
                                   FullWidth="true"
                                   StartIcon="@Icons.Material.Filled.Refresh"
                                   OnClick="RestartWorker"
                                   Disabled="@_isProcessing">
                            راه‌اندازی مجدد Worker
                        </MudButton>
                    </MudStack>
                </MudCardContent>
            </MudCard>
        </MudItem>

        <!-- Execution Log -->
        <MudItem xs="12">
            <MudCard Elevation="2">
                <MudCardHeader>
                    <div class="d-flex justify-space-between align-center w-100">
                        <MudText Typo="Typo.h6">تاریخچه اجرا</MudText>
                        <MudButton Size="Size.Small" 
                                   Variant="Variant.Text" 
                                   Color="Color.Primary"
                                   StartIcon="@Icons.Material.Filled.Refresh"
                                   OnClick="RefreshLog">
                            بروزرسانی
                        </MudButton>
                    </div>
                </MudCardHeader>
                <MudCardContent>
                    @if (_executionLog == null || !_executionLog.Any())
                    {
                        <MudAlert Severity="Severity.Info">هیچ رکوردی یافت نشد</MudAlert>
                    }
                    else
                    {
                        <MudTable T="ExecutionLogModel" Items="@_executionLog" Dense="true" Hover="true" FixedHeader="true" Height="400px">
                            <HeaderContent>
                                <MudTh>زمان</MudTh>
                                <MudTh>هفته</MudTh>
                                <MudTh>وضعیت</MudTh>
                                <MudTh>مدت زمان</MudTh>
                                <MudTh>تعداد پردازش</MudTh>
                                <MudTh>پیام خطا</MudTh>
                            </HeaderContent>
                            <RowTemplate>
                                <MudTd DataLabel="زمان">@PersianDateTime.ConvertToPersianDateTime(context.ExecutionTime)</MudTd>
                                <MudTd DataLabel="هفته">@context.WeekDisplayName</MudTd>
                                <MudTd DataLabel="وضعیت">
                                    <MudChip T="string" 
                                             Color="@(context.Status == "موفق" ? Color.Success : Color.Error)" 
                                             Size="Size.Small">
                                        @context.Status
                                    </MudChip>
                                </MudTd>
                                <MudTd DataLabel="مدت زمان">@context.Duration</MudTd>
                                <MudTd DataLabel="تعداد پردازش">@context.ProcessedCount</MudTd>
                                <MudTd DataLabel="پیام خطا">
                                    <MudText Typo="Typo.body2" Color="@(string.IsNullOrEmpty(context.ErrorMessage) ? Color.Default : Color.Error)">
                                        @(string.IsNullOrEmpty(context.ErrorMessage) ? "-" : context.ErrorMessage)
                                    </MudText>
                                </MudTd>
                            </RowTemplate>
                        </MudTable>
                    }
                </MudCardContent>
            </MudCard>
        </MudItem>
    </MudGrid>

    @if (_isProcessing)
    {
        <MudOverlay Visible="true" DarkBackground="true">
            <MudProgressCircular Color="Color.Primary" Indeterminate="true" Size="Size.Large" />
        </MudOverlay>
    }
</div>

@code {
    [Inject] public CMSMicroservice.Protobuf.Protos.Commission.CommissionContract.CommissionContractClient CommissionClient { get; set; }
    [Inject] public BackOffice.Services.IPersianDateTimeService PersianDateTime { get; set; }

    private WorkerStatus _workerStatus = WorkerStatus.Running;
    private DateTime _lastRunTime = DateTime.Now.AddHours(-2);
    private DateTime _nextRunTime = DateTime.Now.AddDays(1);
    private int _successfulRuns = 45;
    private int _failedRuns = 2;
    private long? _manualWeekDefinitionId;
    private string _manualWeekDisplayName = "";
    private bool _isProcessing = false;
    private List<ExecutionLogModel> _executionLog = new();

    protected override async Task OnInitializedAsync()
    {
        try
        {
            var statusResponse = await CommissionClient.GetWorkerStatusAsync(new CMSMicroservice.Protobuf.Protos.Commission.GetWorkerStatusRequest());
            _workerStatus = statusResponse.IsRunning ? WorkerStatus.Running : WorkerStatus.Paused;
            _lastRunTime = statusResponse.LastRunAt?.ToDateTime() ?? DateTime.MinValue;
            _nextRunTime = statusResponse.NextScheduledRun?.ToDateTime() ?? DateTime.MinValue;
            _successfulRuns = statusResponse.SuccessfulExecutions;
            _failedRuns = statusResponse.FailedExecutions;
            
            await RefreshLog();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری وضعیت: {ex.Message}", Severity.Error);
            _executionLog = new List<ExecutionLogModel>();
        }
    }

    private async Task RunManualCalculation()
    {
        if (!_manualWeekDefinitionId.HasValue || _manualWeekDefinitionId.Value <= 0)
        {
            Snackbar.Add("لطفا هفته را انتخاب کنید", Severity.Warning);
            return;
        }

        var confirmed = await DialogService.ShowMessageBox(
            "اجرای دستی محاسبات",
            $"آیا از اجرای محاسبات برای هفته {_manualWeekDisplayName} اطمینان دارید؟",
            yesText: "بله، اجرا شود", cancelText: "لغو");

        if (confirmed == true)
        {
            _isProcessing = true;
            try
            {
                var request = new CMSMicroservice.Protobuf.Protos.Commission.TriggerWeeklyCalculationRequest
                {
                    WeekDefinitionId = _manualWeekDefinitionId.Value
                };
                await CommissionClient.TriggerWeeklyCalculationAsync(request);
                
                Snackbar.Add($"محاسبات هفته {_manualWeekDisplayName} با موفقیت آغاز شد", Severity.Success);
                _manualWeekDefinitionId = null;
                _manualWeekDisplayName = "";
                await RefreshLog();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در اجرای محاسبات: {ex.Message}", Severity.Error);
            }
            finally
            {
                _isProcessing = false;
            }
        }
    }

    private async Task PauseWorker()
    {
        var confirmed = await DialogService.ShowMessageBox(
            "توقف Worker",
            "این قابلیت فعلا در دسترس نیست",
            yesText: "تایید", cancelText: null);
    }

    private async Task ResumeWorker()
    {
        Snackbar.Add("این قابلیت فعلا در دسترس نیست", Severity.Info);
    }

    private async Task RestartWorker()
    {
        var confirmed = await DialogService.ShowMessageBox(
            "راه‌اندازی مجدد Worker",
            "این قابلیت فعلا در دسترس نیست",
            yesText: "تایید", cancelText: null);
    }

    private async Task RefreshLog()
    {
        try
        {
            var request = new CMSMicroservice.Protobuf.Protos.Commission.GetWorkerExecutionLogsRequest
            {
                PageIndex = 1,
                PageSize = 20
            };
            var response = await CommissionClient.GetWorkerExecutionLogsAsync(request);
            
            _executionLog = response.Models.Select(log => new ExecutionLogModel
            {
                ExecutionTime = log.StartedAt?.ToDateTime() ?? DateTime.MinValue,
                WeekDefinitionId = log.WeekDefinitionId,
                WeekDisplayName = log.WeekDisplayName,
                Status = log.Success ? "موفق" : "ناموفق",
                Duration = $"{log.DurationMs / 1000.0:F1} ثانیه",
                ProcessedCount = log.RecordsProcessed,
                ErrorMessage = log.ErrorMessage ?? ""
            }).ToList();
            
            Snackbar.Add("تاریخچه بروزرسانی شد", Severity.Info);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری تاریخچه: {ex.Message}", Severity.Error);
        }
    }

    private string GetWorkerStatusText()
    {
        return _workerStatus switch
        {
            WorkerStatus.Running => "در حال اجرا",
            WorkerStatus.Paused => "متوقف",
            WorkerStatus.Stopped => "خاموش",
            _ => "نامشخص"
        };
    }

    private enum WorkerStatus
    {
        Running,
        Paused,
        Stopped
    }

    private class ExecutionLogModel
    {
        public DateTime ExecutionTime { get; set; }
        public long WeekDefinitionId { get; set; }
        public string WeekDisplayName { get; set; } = "";
        public string Status { get; set; } = "";
        public string Duration { get; set; } = "";
        public int ProcessedCount { get; set; }
        public string ErrorMessage { get; set; } = "";
    }
}
