using Microsoft.Playwright;

namespace Books.E2E.Tests.Pages.Modals;

/// <summary>
/// Page object for the Cancel Order modal.
/// </summary>
public class CancelOrderModalPage : BasePage
{
    private readonly ILocator _modal;
    private readonly ILocator _warningAlert;
    private readonly ILocator _reasonInput;
    private readonly ILocator _submitButton;
    private readonly ILocator _cancelButton;

    public CancelOrderModalPage(IPage page) : base(page)
    {
        _modal = page.Locator(".ant-modal:has-text('Annuller ordre')");
        _warningAlert = _modal.Locator(".ant-alert-warning");
        _reasonInput = _modal.Locator("textarea");
        _submitButton = _modal.GetByRole(AriaRole.Button, new() { Name = "Annuller ordre" });
        _cancelButton = _modal.GetByRole(AriaRole.Button, new() { Name = "Fortryd" });
    }

    /// <summary>
    /// Waits for the modal to be visible.
    /// </summary>
    public async Task WaitForModalToOpen()
    {
        await _modal.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = 5000 });
    }

    /// <summary>
    /// Checks if the warning alert is visible.
    /// </summary>
    public async Task<bool> IsWarningAlertVisible()
    {
        return await _warningAlert.IsVisibleAsync();
    }

    /// <summary>
    /// Enters the cancellation reason.
    /// </summary>
    public async Task EnterReason(string reason)
    {
        await _reasonInput.ClearAsync();
        await _reasonInput.FillAsync(reason);
    }

    /// <summary>
    /// Submits the form to cancel the order.
    /// </summary>
    public async Task Submit()
    {
        await _submitButton.ClickAsync();
        // Wait for modal to close or show error
        await Task.WhenAny(
            _modal.WaitForAsync(new() { State = WaitForSelectorState.Hidden, Timeout = 10000 }),
            Page.Locator(".ant-form-item-explain-error").WaitForAsync(new() { Timeout = 10000 })
        );
    }

    /// <summary>
    /// Cancels and closes the modal (does not cancel the order).
    /// </summary>
    public async Task Cancel()
    {
        await _cancelButton.ClickAsync();
        await _modal.WaitForAsync(new() { State = WaitForSelectorState.Hidden, Timeout = 5000 });
    }

    /// <summary>
    /// Checks if there are validation errors.
    /// </summary>
    public async Task<bool> HasValidationErrors()
    {
        return await _modal.Locator(".ant-form-item-explain-error").IsVisibleAsync();
    }

    /// <summary>
    /// Checks if the modal is visible.
    /// </summary>
    public async Task<bool> IsVisible()
    {
        return await _modal.IsVisibleAsync();
    }
}
