using ConfigurationPannel.Services;
using Inspectron.Epson.PrintServer.WorkAreaSources;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ConfigurationManager = ConfigurationPannel.Services.ConfigurationManager;

namespace ConfigurationPannel.Pages;

[Authorize]
public class TestPrintModel : PageModel
{
    private readonly ConfigurationManager _configManager;
    private readonly PrintServerHostedService _printServerService;
    private readonly ILogger<TestPrintModel> _logger;

    public TestPrintModel(
        ConfigurationManager configManager,
        PrintServerHostedService printServerService,
        ILogger<TestPrintModel> logger)
    {
        _configManager = configManager;
        _printServerService = printServerService;
        _logger = logger;
    }

    public List<WorkArea> WorkAreas { get; set; } = new();

    [BindProperty]
    public string SelectedWorkAreaId { get; set; } = string.Empty;

    [BindProperty]
    public string PrintContent { get; set; } = string.Empty;

    public string SuccessMessage { get; set; } = string.Empty;
    public string ErrorMessage { get; set; } = string.Empty;

    public async Task<IActionResult> OnGetAsync()
    {
        try
        {
            var config = await _configManager.LoadConfigurationAsync();
            var workAreaSource = new JamesWorkAreaSource(config);
            WorkAreas = await workAreaSource.GetWorkAreasAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error loading test print page");
            ErrorMessage = "Error loading work areas: " + ex.Message;
        }
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        try
        {
            if (string.IsNullOrWhiteSpace(SelectedWorkAreaId))
            {
                ErrorMessage = "Please select a work area";
                return await OnGetAsync();
            }

            if (string.IsNullOrWhiteSpace(PrintContent))
            {
                ErrorMessage = "Please enter content to print";
                return await OnGetAsync();
            }

            var (success, message) = await _printServerService.SubmitPrintJobAsync(
                SelectedWorkAreaId,
                PrintContent);

            if (success)
            {
                SuccessMessage = message;
                PrintContent = string.Empty;
            }
            else
            {
                ErrorMessage = message;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error submitting test print job");
            ErrorMessage = "Error submitting print job: " + ex.Message;
        }

        return await OnGetAsync();
    }
}
