@using System.Globalization
@using Microsoft.Extensions.Localization
@inject DbService DbService
@inject ItemService ItemService
@inject IStringLocalizerFactory LocalizerFactory

<label for="@Id" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">@Label</label>
<div class="flex">
    <div class="relative flex-grow">
        <input type="@(_internalShowPassword ? "text" : "password")" id="@Id" autocomplete="off" class="outline-0 shadow-sm bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-l-lg block w-full p-2.5 pr-16 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white" value="@Value" @oninput="OnInputChanged" placeholder="@Placeholder">
    </div>
    <div class="flex">
        <button type="button" class="@GetVisibilityButtonClasses()" @onclick="TogglePasswordVisibility">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                @if (_internalShowPassword)
                {
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                }
                else
                {
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path>
                }
            </svg>
        </button>
        @if (ShowGenerateButtons)
        {
            <button type="button" id="@($"{Id}-generator-settings")" class="px-3 text-gray-500 dark:text-white bg-gray-200 hover:bg-gray-300 focus:ring-4 focus:outline-none focus:ring-gray-300 font-medium text-sm border-l border-gray-300 dark:border-gray-700 dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-800" @onclick="ShowPasswordSettings">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                </svg>
            </button>
            <button type="button" class="px-3 text-gray-500 dark:text-white bg-gray-200 hover:bg-gray-300 focus:ring-4 focus:outline-none focus:ring-gray-300 font-medium rounded-r-lg text-sm border-l border-gray-300 dark:border-gray-700 dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-800" @onclick="GeneratePassword">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                </svg>
            </button>
        }
    </div>
</div>

@if (ShowGenerateButtons)
{
    @* Inline length / word-count slider, mirroring the browser extension and mobile app so the most-used
       generator control is available directly below the field without having to open the settings popup.
       Reuses the PasswordSettingsPopup resource strings so no new translations are needed. *@
    <div class="pt-2">
        <div class="flex items-center justify-between mb-1">
            <label for="@($"{Id}-inline-length")" class="text-sm font-medium text-gray-700 dark:text-gray-300">
                @(IsDiceware ? Localizer["WordCountLabel"] : string.Format(CultureInfo.CurrentCulture, Localizer["PasswordLengthLabel"], _internalPasswordSettings.Length))
            </label>
            @if (IsDiceware)
            {
                <span class="text-sm text-gray-600 dark:text-gray-400 font-mono">@_internalPasswordSettings.WordCount</span>
            }
        </div>
        @if (IsDiceware)
        {
            <input type="range" id="@($"{Id}-inline-length")" min="@MinWordCount" max="@MaxWordCount" step="1"
                   class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 av-range-slider"
                   value="@_internalPasswordSettings.WordCount" @oninput="HandleWordCountInput">
        }
        else
        {
            <input type="range" id="@($"{Id}-inline-length")" min="@PasswordLengthSlider.SliderMin.ToString(CultureInfo.InvariantCulture)" max="@PasswordLengthSlider.SliderMax.ToString(CultureInfo.InvariantCulture)" step="0.1"
                   class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700 av-range-slider"
                   value="@_sliderValue.ToString(CultureInfo.InvariantCulture)" @oninput="HandleLengthInput">
        }
    </div>
}

@if (IsPasswordSettingsVisible)
{
    <PasswordSettingsPopup
        PasswordSettings="@_internalPasswordSettings"
        IsTemporary="true"
        OnSaveSettings="@HandlePasswordSettingsSaved"
        OnClose="@ClosePasswordSettings" />
}

@code {
    private IStringLocalizer Localizer => LocalizerFactory.Create("Components.Main.Settings.PasswordSettingsPopup", "AliasVault.Client");

    /// <summary>
    /// Inclusive bounds for the Diceware word-count slider.
    /// </summary>
    private const int MinWordCount = AliasClientDb.Models.PasswordGeneratorDefaults.MinWordCount;
    private const int MaxWordCount = AliasClientDb.Models.PasswordGeneratorDefaults.MaxWordCount;

    /// <summary>
    /// Id for the input field.
    /// </summary>
    [Parameter]
    public string Id { get; set; } = string.Empty;

    /// <summary>
    /// Label for the input field.
    /// </summary>
    [Parameter]
    public string Label { get; set; } = "Password";

    /// <summary>
    /// Value of the input field.
    /// </summary>
    [Parameter]
    public string Value { get; set; } = string.Empty;

    /// <summary>
    /// Callback that is triggered when the value changes.
    /// </summary>
    [Parameter]
    public EventCallback<string?> ValueChanged { get; set; }

    /// <summary>
    /// Placeholder text for the input field.
    /// </summary>
    [Parameter]
    public string Placeholder { get; set; } = string.Empty;

    /// <summary>
    /// Controls whether the password is visible in plain text or not.
    /// </summary>
    [Parameter]
    public bool ShowPassword { get; set; } = false;

    /// <summary>
    /// Controls whether the generate and settings buttons are shown.
    /// Set to false for fields like CVV or card number that shouldn't be generated.
    /// </summary>
    [Parameter]
    public bool ShowGenerateButtons { get; set; } = true;

    /// <summary>
    /// Whether the password settings popup is visible.
    /// </summary>
    private bool IsPasswordSettingsVisible { get; set; }

    /// <summary>
    /// Whether the password is visible in plain text or not.
    /// </summary>
    private bool _internalShowPassword;

    /// <summary>
    /// Internal copy of the password settings which can be mutated without affecting the global settings.
    /// </summary>
    private PasswordSettings _internalPasswordSettings = new();

    /// <summary>
    /// The non-linear slider position (0-100) backing the inline password-length slider.
    /// </summary>
    private double _sliderValue;

    /// <summary>
    /// Whether the component has been initialized.
    /// </summary>
    private bool _hasInitialized;

    /// <summary>
    /// Gets a value indicating whether the Diceware (passphrase) generator is currently selected.
    /// </summary>
    private bool IsDiceware => _internalPasswordSettings.Type == "diceware";

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        _internalShowPassword = ShowPassword;
        _internalPasswordSettings = DbService.Settings.PasswordSettings;
        _sliderValue = PasswordLengthSlider.LengthToSlider(_internalPasswordSettings.Length);
    }

    /// <inheritdoc />
    protected override void OnParametersSet()
    {
        base.OnParametersSet();

        if (!_hasInitialized)
        {
            _internalShowPassword = ShowPassword;
            _hasInitialized = true;
        }
    }

    /// <summary>
    /// Gets the CSS classes for the visibility toggle button.
    /// When generate buttons are hidden, this button needs rounded-r-lg to be the last button.
    /// </summary>
    private string GetVisibilityButtonClasses()
    {
        var baseClasses = "px-3 text-gray-500 dark:text-white bg-gray-200 hover:bg-gray-300 focus:ring-4 focus:outline-none focus:ring-gray-300 font-medium text-sm dark:bg-gray-600 dark:hover:bg-gray-700 dark:focus:ring-gray-800";
        return ShowGenerateButtons ? baseClasses : $"{baseClasses} rounded-r-lg";
    }

    /// <summary>
    /// Toggles the password plain text visibility.
    /// </summary>
    private void TogglePasswordVisibility()
    {
        _internalShowPassword = !_internalShowPassword;
    }

    /// <summary>
    /// Shows the password settings popup.
    /// </summary>
    private void ShowPasswordSettings()
    {
        IsPasswordSettingsVisible = true;
    }

    /// <summary>
    /// Closes the password settings popup.
    /// </summary>
    private void ClosePasswordSettings()
    {
        IsPasswordSettingsVisible = false;
    }

    /// <summary>
    /// Updates the local value when the input field changes.
    /// </summary>
    private async Task OnInputChanged(ChangeEventArgs e)
    {
        Value = e.Value?.ToString() ?? string.Empty;
        await ValueChanged.InvokeAsync(Value);
    }

    /// <summary>
    /// Updates current password when password settings have been changed.
    /// </summary>
    private async Task HandlePasswordSettingsSaved((PasswordSettings settings, string generatedPassword) args)
    {
        _internalPasswordSettings = args.settings;
        _sliderValue = PasswordLengthSlider.LengthToSlider(_internalPasswordSettings.Length);
        _internalShowPassword = true;
        Value = args.generatedPassword;
        await ValueChanged.InvokeAsync(Value);
    }

    /// <summary>
    /// Handle input from the inline password-length slider: update the length and regenerate the password.
    /// </summary>
    private async Task HandleLengthInput(ChangeEventArgs e)
    {
        if (double.TryParse(e.Value?.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var sliderValue))
        {
            _sliderValue = sliderValue;
            _internalPasswordSettings.Length = PasswordLengthSlider.SliderToLength(sliderValue);
            await RegenerateFromSlider();
        }
    }

    /// <summary>
    /// Handle input from the inline Diceware word-count slider: update the word count and regenerate the passphrase.
    /// </summary>
    private async Task HandleWordCountInput(ChangeEventArgs e)
    {
        if (int.TryParse(e.Value?.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var wordCount))
        {
            _internalPasswordSettings.WordCount = wordCount;
            await RegenerateFromSlider();
        }
    }

    /// <summary>
    /// Regenerate the password from the current inline settings and surface it in the field.
    /// </summary>
    private async Task RegenerateFromSlider()
    {
        Value = await ItemService.GenerateRandomPasswordAsync(_internalPasswordSettings);
        _internalShowPassword = true;
        await ValueChanged.InvokeAsync(Value);
    }

    /// <summary>
    /// Generates a new password.
    /// </summary>
    private async Task GeneratePassword()
    {
        string newPassword = await ItemService.GenerateRandomPasswordAsync(_internalPasswordSettings);

        // Update the local value.
        Value = newPassword;
        await ValueChanged.InvokeAsync(Value);

        // Make password visible when it's (re)generated.
        _internalShowPassword = true;
    }
}
