@page "/account/forgot-password"
@layout AuthenticationLayout
@using System.ComponentModel.DataAnnotations
@using Indotalent.Shared.Consts
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime
@inject ISnackbar Snackbar
@inject NavigationManager Navigation

<PageTitle>Forgot Password - @GlobalConsts.AppInitial</PageTitle>

<style>
    /* ===== PAGE HEADER ===== */
    .page-header {
        text-align: center;
        margin-bottom: 1.5rem;
    }

    .page-header h2 {
        font-size: 1.5rem;
        font-weight: 700;
        color: #0f172a;
        margin-bottom: 0.25rem;
    }

    .page-header p {
        font-size: 0.8125rem;
        color: #64748b;
        margin: 0;
    }

    /* ===== FORM LABELS ===== */
    .form-label {
        font-size: 0.8125rem;
        font-weight: 600;
        color: #475569;
        margin-bottom: 0.375rem;
        display: block;
    }

    /* ===== MISC ===== */
    .w-100 { width: 100%; }
    .mb-4 { margin-bottom: 1rem; }
    .mb-6 { margin-bottom: 1.5rem; }
    .mt-6 { margin-top: 1.5rem; }
    .text-center { text-align: center; }
</style>

<div class="page-header">
    <h2>Forgot Password?</h2>
    <p>Enter your email address below and we'll send you a link to reset your password.</p>
</div>

<MudForm @ref="form" @bind-IsValid="@success">

    <span class="form-label">Email Address</span>
    <MudTextField T="string"
                  @bind-Value="model.Email"
                  Variant="Variant.Outlined"
                  Placeholder="name@example.com"
                  Margin="Margin.Dense"
                  Adornment="Adornment.Start"
                  AdornmentIcon="@Icons.Material.Filled.Email"
                  Required="true"
                  Validation="@(new EmailAddressAttribute() { ErrorMessage = "Invalid email address format" })"
                  For="@(() => model.Email)"
                  Class="mb-6"
                  Style="border-radius: 0.5rem;" />

    <MudButton Variant="Variant.Filled"
               Color="Color.Primary"
               Size="Size.Large"
               FullWidth="true"
               Disabled="!success || isProcessing"
               OnClick="HandleForgotPassword"
               Style="text-transform:none; border-radius: 0.5rem; height: 48px; font-weight: 600;">
        @if (isProcessing)
        {
            <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" Color="Color.Inherit" />
            <span class="ms-2">Sending link...</span>
        }
        else
        {
            <span>Send Reset Link</span>
        }
    </MudButton>
</MudForm>

<div class="text-center mt-6">
    <MudText Typo="Typo.body2">
        Remember your password?
        <MudLink Href="/account/login" Style="color: #6366F1; font-weight: 600; margin-left: 0.25rem;">Back to Sign In</MudLink>
    </MudText>
</div>

@code {
    private MudForm form = default!;
    private bool success;
    private bool isProcessing;
    private ForgotPasswordModel model = new();

    private class ForgotPasswordModel
    {
        public string Email { get; set; } = "";
    }

    private async Task HandleForgotPassword()
    {
        await form.Validate();
        if (!success) return;

        isProcessing = true;
        StateHasChanged();

        var result = await JSRuntime.InvokeAsync<ApiResponse>("apiForgotPassword", model.Email);

        if (result.Status == 200)
        {
            Snackbar.Add("If your email is registered, a reset link has been sent.", Severity.Success);
            await Task.Delay(500);
            Navigation.NavigateTo("/account/login");
        }
        else
        {
            Snackbar.Add(result.Title ?? "Failed to send reset link", Severity.Error);
        }

        isProcessing = false;
        StateHasChanged();
    }

    private class ApiResponse
    {
        public int Status { get; set; }
        public string? Title { get; set; }
    }
}

<script>
    window.apiForgotPassword = async (email) => {
        try {
            const response = await fetch('/api/account/forgot-password', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email })
            });

            if (response.ok) {
                return { status: 200, title: 'Success' };
            } else {
                const data = await response.json();
                let msg = 'Error processing request';
                if (data.errors && data.errors.length > 0) msg = data.errors[0];
                return { status: response.status, title: msg };
            }
        } catch (error) {
            return { status: 500, title: 'Network error' };
        }
    };
</script>