using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Input;
using FootwearTest.Models;
using FootwearTest.Services;
using Microsoft.Extensions.Logging;

namespace FootwearTest.ViewModels;

public partial class HistoryViewModel : ViewModelBase
{
    private readonly TestRunRepository _repository;
    private readonly ReportService _reportService;
    private readonly ExcelReportService _excelReportService;
    private readonly ILogger<HistoryViewModel> _logger;

    public HistoryViewModel(
        TestRunRepository repository,
        ReportService reportService,
        ExcelReportService excelReportService,
        ILogger<HistoryViewModel> logger)
    {
        _repository = repository;
        _reportService = reportService;
        _excelReportService = excelReportService;
        _logger = logger;
        LoadCommand = new AsyncRelayCommand(LoadAsync);
        ExportSelectedExcelCommand = new AsyncRelayCommand(ExportSelectedExcelAsync);
        _ = LoadAsync();
    }

    public ObservableCollection<TestRunSummary> Runs { get; } = [];
    public IAsyncRelayCommand LoadCommand { get; }
    public IAsyncRelayCommand ExportSelectedExcelCommand { get; }

    private TestRunSummary? _selectedRun;
    private string _selectedReportText = "选择一条历史记录查看报告。";
    private string _exportStatusText = "选择历史记录后可导出完整 Excel 报告。";

    public TestRunSummary? SelectedRun
    {
        get => _selectedRun;
        set
        {
            if (SetProperty(ref _selectedRun, value))
            {
                _ = LoadSelectedReportAsync(value);
            }
        }
    }

    public string SelectedReportText
    {
        get => _selectedReportText;
        set => SetProperty(ref _selectedReportText, value);
    }

    public string ExportStatusText
    {
        get => _exportStatusText;
        set => SetProperty(ref _exportStatusText, value);
    }

    private async Task LoadAsync()
    {
        try
        {
            Runs.Clear();
            foreach (var run in await _repository.GetRecentAsync())
            {
                Runs.Add(run);
            }

            _logger.LogInformation("History records loaded. Count={Count}", Runs.Count);
        }
        catch (Exception ex)
        {
            ExportStatusText = $"历史记录加载失败: {ex.Message}";
            _logger.LogError(ex, "Failed to load history records");
        }
    }

    private async Task LoadSelectedReportAsync(TestRunSummary? value)
    {
        if (value is null)
        {
            SelectedReportText = "选择一条历史记录查看报告。";
            return;
        }

        var record = await _repository.GetByIdAsync(value.Id);
        SelectedReportText = record is null ? "记录不存在。" : _reportService.CreateTextReport(record);
        ExportStatusText = record is null ? "记录不存在，无法导出。" : "可导出所选记录的完整 Excel 报告。";
    }

    private async Task ExportSelectedExcelAsync()
    {
        if (SelectedRun is null)
        {
            ExportStatusText = "请先选择一条历史记录。";
            return;
        }

        var record = await _repository.GetByIdAsync(SelectedRun.Id);
        if (record is null)
        {
            ExportStatusText = "记录不存在，无法导出。";
            return;
        }

        try
        {
            var path = await _excelReportService.ExportAsync(record);
            ExportStatusText = $"已导出 Excel: {path}";
            _logger.LogInformation("Selected history record exported. RecordId={RecordId}, Path={Path}", record.Id, path);
        }
        catch (Exception ex)
        {
            ExportStatusText = $"导出失败: {ex.Message}";
            _logger.LogError(ex, "Failed to export selected history record. RecordId={RecordId}", record.Id);
        }
    }
}
