@page "/reset-password"
@using WebClientTpos.Shared.DTOs
@using WebClientTpos.Shared
@inject HttpClient Http
@inject NavigationManager Navigation
@inject IStringLocalizer<ResetPassword> L

@* 
    EN: Reset password page with token validation.
    VI: Trang đặt lại mật khẩu với xác thực token.
*@

<PageTitle>@L["Auth_ResetPassword_Title"]</PageTitle>

<div class="auth-container">
    <section class="auth-card">
        <h1 class="auth-title">@L["Auth_ResetPassword_Title"]</h1>
        <p class="auth-subtitle">@L["Auth_ResetPassword_Subtitle"]</p>
        
        @if (invalidToken)
        {
            <div class="alert alert-error">
                @L["Auth_ResetPassword_InvalidToken"]
            </div>
            <div class="auth-footer">
                <a href="/forgot-password" class="link-primary">@L["Auth_ForgotPassword_Title"]</a>
            </div>
        }
        else
        {
            <EditForm Model="@resetPasswordModel" OnValidSubmit="HandleResetPassword" FormName="ResetPasswordForm">
                <DataAnnotationsValidator />
                
                <div class="form-group">
                    <label for="new-password">@L["Auth_ResetPassword_NewPassword"] *</label>
                    <InputText id="new-password" 
                              @bind-Value="resetPasswordModel.NewPassword" 
                              type="password" 
                              class="form-input" 
                              placeholder="••••••••"
                              autocomplete="new-password" />
                    <small class="form-hint">@L["Auth_ResetPassword_PasswordHint"]</small>
                    <ValidationMessage For="() => resetPasswordModel.NewPassword" class="validation-message" />
                </div>
                
                <div class="form-group">
                    <label for="confirm-password">@L["Auth_ResetPassword_ConfirmPassword"] *</label>
                    <InputText id="confirm-password" 
                              @bind-Value="resetPasswordModel.ConfirmPassword" 
                              type="password" 
                              class="form-input" 
                              placeholder="••••••••"
                              autocomplete="new-password" />
                    <ValidationMessage For="() => resetPasswordModel.ConfirmPassword" class="validation-message" />
                </div>
                
                <button type="submit" class="btn-primary btn-full" disabled="@isSubmitting">
                    @if (isSubmitting)
                    {
                        <span class="spinner-small"></span>
                        <span>@L["Common_Loading"]</span>
                    }
                    else
                    {
                        @L["Auth_ResetPassword_Submit"]
                    }
                </button>
            </EditForm>
            
            @if (!string.IsNullOrEmpty(message))
            {
                <div class="alert @(success ? "alert-success" : "alert-error")">
                    @message
                </div>
            }
        }
    </section>
</div>

@code {
    private ResetPasswordDto resetPasswordModel = new();
    private bool isSubmitting = false;
    private string message = "";
    private bool success = false;
    private bool invalidToken = false;

    protected override void OnInitialized()
    {
        // EN: Parse query parameters for token and email
        // VI: Phân tích query parameters cho token và email
        var uri = new Uri(Navigation.Uri);
        var query = uri.Query;
        
        if (!string.IsNullOrEmpty(query))
        {
            var queryParams = System.Web.HttpUtility.ParseQueryString(query);
            var token = queryParams["token"];
            var email = queryParams["email"];

            if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(email))
            {
                resetPasswordModel.Token = token;
                resetPasswordModel.Email = email;
            }
            else
            {
                invalidToken = true;
            }
        }
        else
        {
            invalidToken = true;
        }
    }

    /// <summary>
    /// EN: Handle reset password form submission.
    /// VI: Xử lý submit form đặt lại mật khẩu.
    /// </summary>
    private async Task HandleResetPassword()
    {
        isSubmitting = true;
        message = "";

        try
        {
            var response = await Http.PostAsJsonAsync("api/auth/reset-password", resetPasswordModel);
            
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<ApiResponse<object>>();
                if (result?.Success == true)
                {
                    success = true;
                    message = L["Auth_ResetPassword_Success"];
                    
                    // EN: Redirect to login after 2 seconds
                    // VI: Chuyển hướng đến đăng nhập sau 2 giây
                    await Task.Delay(2000);
                    Navigation.NavigateTo("/login");
                }
                else
                {
                    success = false;
                    message = result?.Error ?? L["Auth_ResetPassword_Error"];
                }
            }
            else
            {
                success = false;
                message = L["Auth_ResetPassword_Error"];
            }
        }
        catch (Exception ex)
        {
            success = false;
            message = $"{L["Common_Error"]}: {ex.Message}";
        }
        finally
        {
            isSubmitting = false;
        }
    }
}
