@using AliasVault.Client.Main.Models
@using AliasVault.Client.Main.Components.Layout
@using Microsoft.Extensions.Localization

@inject IStringLocalizerFactory LocalizerFactory

<div class="relative flex items-center gap-2">
    <button @onclick="ToggleDropdown" id="@($"filterButton-{InstanceId}")" class="flex items-center gap-2 text-gray-900 dark:text-white hover:text-gray-700 dark:hover:text-gray-300 focus:outline-none">
        <h1 class="flex items-baseline gap-1.5 text-xl font-semibold tracking-tight text-gray-900 dark:text-white sm:text-2xl">
            <span>@Title</span>
            @if (Count.HasValue)
            {
                <span class="text-base text-gray-500 dark:text-gray-400">(@Count.Value)</span>
            }
        </h1>
        <svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="6 9 12 15 18 9" />
        </svg>
    </button>

    @TitleActions

    @if (_isOpen)
    {
        <ClickOutsideHandler OnClose="Close" ContentId="@($"filterDropdown-{InstanceId},filterButton-{InstanceId}")">
            <div id="@($"filterDropdown-{InstanceId}")" class="absolute left-0 top-full z-40 mt-2 w-56 origin-top-left rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none dark:bg-gray-700">
                <div class="py-1">
                    @* All items + show folders toggle *@
                    <div class="flex items-center justify-between px-4 py-2 @(IsActive(ItemFilterType.All) ? "bg-orange-50 dark:bg-orange-900/20" : string.Empty)">
                        <button @onclick="() => PickFilter(ItemFilterType.All)" class="text-left text-sm hover:text-gray-900 dark:hover:text-white @(IsActive(ItemFilterType.All) ? "text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                            @Localizer["FilterAllOption"]
                        </button>
                        @if (ShowFoldersToggle && OnToggleShowFolders.HasDelegate)
                        {
                            <button @onclick="ToggleFoldersAsync" @onclick:stopPropagation="true" class="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300">
                                <span>@Localizer["ShowFoldersOption"]</span>
                                <svg class="w-5 h-5 @(ShowFolders ? "text-orange-500 dark:text-orange-400" : "text-gray-400 dark:text-gray-500")" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                    <rect x="3" y="3" width="18" height="18" rx="2" />
                                    @if (ShowFolders)
                                    {
                                        <polyline points="7 12 10 15 17 8" />
                                    }
                                </svg>
                            </button>
                        }
                    </div>
                    <div class="border-t border-gray-200 dark:border-gray-600 my-1"></div>

                    @* Item type filters with icons *@
                    <button @onclick="() => PickFilter(ItemFilterType.Login)" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center gap-2 @(IsActive(ItemFilterType.Login) ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        <svg class="w-5 h-5 @(IsActive(ItemFilterType.Login) ? "text-orange-500 dark:text-orange-400" : "text-gray-400 dark:text-gray-500")" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
                        </svg>
                        @ItemTypeSelectorLocalizer["TypeLogin"]
                    </button>
                    <button @onclick="() => PickFilter(ItemFilterType.Alias)" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center gap-2 @(IsActive(ItemFilterType.Alias) ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        <svg class="w-5 h-5 @(IsActive(ItemFilterType.Alias) ? "text-orange-500 dark:text-orange-400" : "text-gray-400 dark:text-gray-500")" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                        </svg>
                        @ItemTypeSelectorLocalizer["TypeAlias"]
                    </button>
                    <button @onclick="() => PickFilter(ItemFilterType.CreditCard)" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center gap-2 @(IsActive(ItemFilterType.CreditCard) ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        <svg class="w-5 h-5 @(IsActive(ItemFilterType.CreditCard) ? "text-orange-500 dark:text-orange-400" : "text-gray-400 dark:text-gray-500")" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                        </svg>
                        @ItemTypeSelectorLocalizer["TypeCreditCard"]
                    </button>
                    <button @onclick="() => PickFilter(ItemFilterType.Note)" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center gap-2 @(IsActive(ItemFilterType.Note) ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        <svg class="w-5 h-5 @(IsActive(ItemFilterType.Note) ? "text-orange-500 dark:text-orange-400" : "text-gray-400 dark:text-gray-500")" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        @ItemTypeSelectorLocalizer["TypeNote"]
                    </button>

                    <div class="border-t border-gray-200 dark:border-gray-600 my-1"></div>

                    @* Special filters *@
                    <button @onclick="() => PickFilter(ItemFilterType.Passkeys)" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 @(IsActive(ItemFilterType.Passkeys) ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        @Localizer["FilterPasskeysOption"]
                    </button>
                    <button @onclick="() => PickFilter(ItemFilterType.Attachments)" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 @(IsActive(ItemFilterType.Attachments) ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        @Localizer["FilterAttachmentsOption"]
                    </button>
                    <button @onclick="() => PickFilter(ItemFilterType.Totp)" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 @(IsActive(ItemFilterType.Totp) ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        @Localizer["FilterTotpOption"]
                    </button>

                    <div class="border-t border-gray-200 dark:border-gray-600 my-1"></div>

                    @* Recently deleted link *@
                    <button @onclick="PickRecentlyDeleted" class="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center justify-between @(IsRecentlyDeletedActive ? "bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400" : "text-gray-700 dark:text-gray-300")">
                        <span>@Localizer["FilterRecentlyDeletedOption"]</span>
                        @if (RecentlyDeletedCount > 0)
                        {
                            <span class="@(IsRecentlyDeletedActive ? "text-orange-500 dark:text-orange-400" : "text-gray-400 dark:text-gray-500")">@RecentlyDeletedCount</span>
                        }
                    </button>
                </div>
            </div>
        </ClickOutsideHandler>
    }
</div>

@code {
    private bool _isOpen;

    private IStringLocalizer Localizer => LocalizerFactory.Create("Pages.Main.Items.Home", "AliasVault.Client");
    private IStringLocalizer ItemTypeSelectorLocalizer => LocalizerFactory.Create("Components.Main.Items.ItemTypeSelector", "AliasVault.Client");

    /// <summary>
    /// Stable identifier used to make the dropdown button/menu DOM ids unique when multiple
    /// instances are on the page (ClickOutsideHandler relies on element ids).
    /// </summary>
    [Parameter]
    public string InstanceId { get; set; } = Guid.NewGuid().ToString("N")[..8];

    /// <summary>Title text shown on the trigger button.</summary>
    [Parameter, EditorRequired]
    public string Title { get; set; } = string.Empty;

    /// <summary>Optional count badge shown next to the title.</summary>
    [Parameter]
    public int? Count { get; set; }

    /// <summary>Currently active item filter, or null when the page itself isn't an item filter (e.g. Recently Deleted).</summary>
    [Parameter]
    public ItemFilterType? ActiveFilter { get; set; }

    /// <summary>True when the Recently Deleted page is the active selection.</summary>
    [Parameter]
    public bool IsRecentlyDeletedActive { get; set; }

    /// <summary>Number of items in Recently Deleted (shown as a badge).</summary>
    [Parameter]
    public int RecentlyDeletedCount { get; set; }

    /// <summary>Whether to render the "Show folders" toggle next to the All filter.</summary>
    [Parameter]
    public bool ShowFoldersToggle { get; set; }

    /// <summary>Current value of the "Show folders" preference.</summary>
    [Parameter]
    public bool ShowFolders { get; set; }

    /// <summary>Optional render fragment placed next to the trigger button (e.g. folder edit/delete buttons).</summary>
    [Parameter]
    public RenderFragment? TitleActions { get; set; }

    /// <summary>Fires when the user picks a filter option.</summary>
    [Parameter]
    public EventCallback<ItemFilterType> OnSelectFilter { get; set; }

    /// <summary>Fires when the user picks "Recently deleted".</summary>
    [Parameter]
    public EventCallback OnSelectRecentlyDeleted { get; set; }

    /// <summary>Fires when the user toggles the "Show folders" preference.</summary>
    [Parameter]
    public EventCallback OnToggleShowFolders { get; set; }

    private bool IsActive(ItemFilterType filter) => !IsRecentlyDeletedActive && ActiveFilter == filter;

    private void ToggleDropdown()
    {
        _isOpen = !_isOpen;
    }

    private void Close()
    {
        _isOpen = false;
        StateHasChanged();
    }

    private async Task PickFilter(ItemFilterType filter)
    {
        _isOpen = false;
        await OnSelectFilter.InvokeAsync(filter);
    }

    private async Task PickRecentlyDeleted()
    {
        _isOpen = false;
        await OnSelectRecentlyDeleted.InvokeAsync();
    }

    private async Task ToggleFoldersAsync()
    {
        _isOpen = false;
        await OnToggleShowFolders.InvokeAsync();
    }
}
