@using Indotalent.Features.Setting.SystemUser
@using Indotalent.Features.Setting.SystemUser.Cqrs
@using Indotalent.Shared.Utils
@using MudBlazor
@inject SystemUserService SystemUserService
@inject ISnackbar Snackbar

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
    <div class="d-flex align-center gap-4">
        <MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
        <div>
            <MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Security: Change Password</MudText>
            <MudText Typo="Typo.body2" Style="color: #64748b;">Manage password security for account: @Data.FullName</MudText>
        </div>
    </div>
</MudPaper>

<MudGrid Spacing="3">
    <MudItem xs="12" sm="7">
        <MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA; height: 100%;">
            <MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Manual Password Overwrite</MudText>
            <MudDivider Class="mt-2 mb-6" />
            
            <MudForm @ref="_form" Model="_model" Validation="@(_validator.ValidateValue())">
                <MudGrid Spacing="3">
                    <MudItem xs="12">
                        <MudText Typo="Typo.subtitle2" Class="mb-1">New Password</MudText>
                        <MudTextField @bind-Value="_model.NewPassword"
                                      For="@(() => _model.NewPassword)"
                                      InputType="InputType.Password"
                                      Variant="Variant.Outlined"
                                      Margin="Margin.Dense"
                                      FullWidth="true" />
                    </MudItem>

                    <MudItem xs="12">
                        <MudText Typo="Typo.subtitle2" Class="mb-1">Confirm New Password</MudText>
                        <MudTextField @bind-Value="_model.ConfirmPassword"
                                      For="@(() => _model.ConfirmPassword)"
                                      InputType="InputType.Password"
                                      Variant="Variant.Outlined"
                                      Margin="Margin.Dense"
                                      FullWidth="true" />
                    </MudItem>
                </MudGrid>

                <div class="d-flex justify-end gap-2 mt-8">
                    <MudButton OnClick="() => OnCancel.InvokeAsync()"
                               Variant="Variant.Outlined"
                               Disabled="_processing"
                               Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">
                        Cancel
                    </MudButton>
                    <MudButton Color="Color.Primary"
                               Variant="Variant.Filled"
                               OnClick="SubmitManual"
                               Disabled="_processing"
                               Style="border-radius: 4px; text-transform: none; font-weight: 700;">
                        @if (_processing)
                        {
                            <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                            <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
                        }
                        else
                        {
                            <MudText>Set New Password</MudText>
                        }
                    </MudButton>
                </div>
            </MudForm>
        </MudPaper>
    </MudItem>

    <MudItem xs="12" sm="5">
        <MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA; height: 100%; background-color: #F8FAFC;">
            <MudText Typo="Typo.button" Color="Color.Info" Style="font-weight: 800;">Password Reset Link</MudText>
            <MudDivider Class="mt-2 mb-4" />
            
            <MudText Typo="Typo.body2" Class="mb-4">
                Instead of setting a password manually, you can send a secure reset link to the user's registered email:
            </MudText>
            
            <MudChip T="string" Color="Color.Info" Variant="Variant.Text" Icon="@Icons.Material.Filled.Email" Class="mb-6">@Data.Email</MudChip>

            <MudButton Color="Color.Info"
                       Variant="Variant.Outlined"
                       OnClick="SendResetLink"
                       Disabled="_processingReset"
                       FullWidth="true"
                       StartIcon="@Icons.Material.Filled.Send"
                       Style="background:white; border-radius: 0px; text-transform: none; font-weight: 700; height: 48px;">
                @if (_processingReset)
                {
                    <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                    <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Sending...</MudText>
                }
                else
                {
                    <MudText>Send Forgot Password Email</MudText>
                }
            </MudButton>
            
            <MudAlert Severity="Severity.Info" Dense="true" Class="mt-4" Square="true" Style="font-size: 12px;">
                The user will receive an email with instructions to set their own password.
            </MudAlert>
        </MudPaper>
    </MudItem>
</MudGrid>

@code {
    [Parameter] public UpdateSystemUserRequest Data { get; set; } = new();
    [Parameter] public EventCallback OnCancel { get; set; }
    [Parameter] public EventCallback OnSuccess { get; set; }

    private MudForm _form = default!;
    private ChangePasswordRequest _model = new();
    private ChangePasswordValidator _validator = new();
    
    private bool _processing = false;
    private bool _processingReset = false;

    protected override void OnInitialized()
    {
        _model.UserId = Data.Id ?? string.Empty;
    }

    private async Task SubmitManual()
    {
        await _form.Validate();
        if (!_form.IsValid) return;

        _processing = true;
        try
        {
            var response = await SystemUserService.ChangePasswordAsync(_model);            
            await Task.Delay(500);
            if (response != null && response.IsSuccess)
            {
                Snackbar.Add("Password updated successfully", Severity.Success);
                await OnSuccess.InvokeAsync();
            }
        }
        finally
        {
            _processing = false;
        }
    }

    private async Task SendResetLink()
    {
        _processingReset = true;
        try
        {
            var success = await SystemUserService.SendResetLinkAsync(Data.Id ?? string.Empty);
            await Task.Delay(500);
            if (success)
            {
                Snackbar.Add("Reset link sent to user email", Severity.Success);
                await OnSuccess.InvokeAsync();
            }
        }
        finally
        {
            _processingReset = false;
        }
    }
}