@page "/profile/password"
@using System.ComponentModel.DataAnnotations
@using MudBlazor
@using Indotalent.Features.Profile.Password
@using Indotalent.Features.Profile.Password.Cqrs
@using Indotalent.ConfigBackEnd.Interfaces
@using Indotalent.Shared.Utils
@inject ISnackbar Snackbar
@inject PasswordService PasswordService
@inject ICurrentUserService CurrentUserService

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between">
    <div>
        <MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Security Settings</MudText>
        <MudText Typo="Typo.body2" Style="color: #64748b;">Manage your password and protect your account security.</MudText>
    </div>

    <div class="d-flex align-center gap-2">
        <MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
        <MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
        <MudText Typo="Typo.caption" Style="color: #94a3b8;">Profile</MudText>
        <MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
        <MudText Typo="Typo.caption" Style="font-weight: 600; color: #1a1a1a;">Password</MudText>
    </div>
</MudPaper>

<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; background-color: #ffffff;">
    <MudForm @ref="_form" Model="_model" Validation="_validator.ValidateValue()" ValidationDelay="300">
        <MudStack Spacing="8">
            <MudGrid>
                <MudItem xs="12" md="4">
                    <MudText Typo="Typo.h6" Class="fw-bold">Change Password</MudText>
                    <MudText Typo="Typo.body2">Update your password to keep your account secure. We recommend using a strong password.</MudText>
                </MudItem>
                <MudItem xs="12" md="8">
                    <MudStack Spacing="4">
                        <div>
                            <MudText Typo="Typo.subtitle2" Class="mb-2">Current Password</MudText>
                            <MudTextField @bind-Value="_model.CurrentPassword"
                                          For="@(() => _model.CurrentPassword)"
                                          Variant="Variant.Outlined"
                                          FullWidth="true"
                                          Margin="Margin.Dense"
                                          InputType="@_currentPasswordInput"
                                          Adornment="Adornment.End"
                                          AdornmentIcon="@_currentPasswordIcon"
                                          OnAdornmentClick="ToggleCurrentPasswordVisibility" />
                        </div>

                        <MudDivider Class="my-2" />

                        <div>
                            <MudText Typo="Typo.subtitle2" Class="mb-2">New Password</MudText>
                            <MudTextField @bind-Value="_model.NewPassword"
                                          For="@(() => _model.NewPassword)"
                                          Variant="Variant.Outlined"
                                          FullWidth="true"
                                          Margin="Margin.Dense"
                                          InputType="@_newPasswordInput"
                                          Adornment="Adornment.End"
                                          AdornmentIcon="@_newPasswordIcon"
                                          OnAdornmentClick="ToggleNewPasswordVisibility"
                                          HelperText="Minimum 4 characters with numbers and symbols" />
                        </div>

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

            <div class="d-flex justify-end align-center gap-4 mt-4">
                <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="UpdatePassword" Disabled="@_isProcessing">
                    @if (_isProcessing)
                    {
                        <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                        <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Updating Password...</MudText>
                    }
                    else
                    {
                        <MudText>Update Password</MudText>
                    }
                </MudButton>
            </div>
        </MudStack>
    </MudForm>
</MudPaper>

@code {
    private MudForm _form = default!;
    private UpdatePasswordValidator _validator = new();
    private bool _isProcessing = false;
    private PasswordChangeModel _model = new();

    private bool _currentPasswordVisibility;
    private InputType _currentPasswordInput = InputType.Password;
    private string _currentPasswordIcon = Icons.Material.Filled.VisibilityOff;

    private bool _newPasswordVisibility;
    private InputType _newPasswordInput = InputType.Password;
    private string _newPasswordIcon = Icons.Material.Filled.VisibilityOff;

    private void ToggleCurrentPasswordVisibility()
    {
        if (_currentPasswordVisibility)
        {
            _currentPasswordVisibility = false;
            _currentPasswordIcon = Icons.Material.Filled.VisibilityOff;
            _currentPasswordInput = InputType.Password;
        }
        else
        {
            _currentPasswordVisibility = true;
            _currentPasswordIcon = Icons.Material.Filled.Visibility;
            _currentPasswordInput = InputType.Text;
        }
    }

    private void ToggleNewPasswordVisibility()
    {
        if (_newPasswordVisibility)
        {
            _newPasswordVisibility = false;
            _newPasswordIcon = Icons.Material.Filled.VisibilityOff;
            _newPasswordInput = InputType.Password;
        }
        else
        {
            _newPasswordVisibility = true;
            _newPasswordIcon = Icons.Material.Filled.Visibility;
            _newPasswordInput = InputType.Text;
        }
    }

    private async Task UpdatePassword()
    {
        await _form.Validate();

        if (!_form.IsValid)
        {
            Snackbar.Add("Please correct the validation errors.", Severity.Warning);
            return;
        }

        if (_model.NewPassword != _model.ConfirmPassword)
        {
            Snackbar.Add("New password and confirmation do not match.", Severity.Error);
            return;
        }

        var userId = CurrentUserService.UserId;
        if (string.IsNullOrEmpty(userId))
        {
            Snackbar.Add("User session not found.", Severity.Error);
            return;
        }

        _isProcessing = true;

        var request = new UpdatePasswordRequest
        {
            Id = userId,
            CurrentPassword = _model.CurrentPassword,
            NewPassword = _model.NewPassword
        };

        var response = await PasswordService.UpdatePasswordAsync(request);
        await Task.Delay(500);

        if (response != null && response.IsSuccess)
        {
            Snackbar.Add("Password updated successfully!", Severity.Success);
            _model = new PasswordChangeModel();
            await _form.ResetAsync();
        }
        else
        {
            Snackbar.Add(response?.Message ?? "Failed to update password", Severity.Error);
        }

        _isProcessing = false;
    }

    public class PasswordChangeModel : UpdatePasswordRequest
    {
        public string ConfirmPassword { get; set; } = string.Empty;
    }
}