@using AliasVault.RazorComponents.Tables
@using AliasVault.Client.Main.Models
@inject NavigationManager NavigationManager

<SortableTable Columns="@_tableColumns" SortColumn="@SortColumn" SortDirection="@CurrentSortDirection" OnSortChanged="HandleSortChanged">
    @foreach (var credential in DisplayedCredentials)
    {
        <SortableTableRow Class="cursor-pointer" OnClick="@(() => NavigateToCredential(credential.Id))">
            <SortableTableColumn Padding="false">
                <div class="flex items-center space-x-2 py-2 pl-2">
                    <DisplayFavicon FaviconBytes="@credential.Logo" Width="24" />
                    <span class="font-bold ml-2">@credential.Service</span>
                </div>
            </SortableTableColumn>
            <SortableTableColumn Padding="false">@credential.Username</SortableTableColumn>
            <SortableTableColumn Padding="false">@credential.Email</SortableTableColumn>
            <SortableTableColumn Padding="false">@credential.CreatedAt.ToString("yyyy-MM-dd")</SortableTableColumn>
        </SortableTableRow>
    }
</SortableTable>

@code {
    /// <summary>
    /// Gets or sets the list of credentials to show.
    /// </summary>
    [Parameter]
    public List<ItemListEntry> Credentials { get; set; } = [];

    /// <summary>
    /// Gets or sets the sort order for the credentials (used to determine initial table state).
    /// </summary>
    [Parameter]
    public CredentialSortOrder SortOrder { get; set; } = CredentialSortOrder.OldestFirst;

    /// <summary>
    /// Gets or sets the column to sort by.
    /// </summary>
    private string SortColumn { get; set; } = "CreatedAt";

    /// <summary>
    /// Gets or sets the current sort direction for table column sorting.
    /// </summary>
    private SortDirection CurrentSortDirection { get; set; } = SortDirection.Ascending;

    /// <summary>
    /// Gets or sets whether the user has explicitly clicked a column to sort.
    /// </summary>
    private bool UserHasClickedColumn { get; set; } = false;

    /// <summary>
    /// Gets or sets the columns to show in the table.
    /// </summary>
    private readonly List<TableColumn> _tableColumns = [
        new TableColumn { Title = "Service", PropertyName = "Service" },
        new TableColumn { Title = "Username", PropertyName = "Username" },
        new TableColumn { Title = "Email", PropertyName = "Email" },
        new TableColumn { Title = "Created", PropertyName = "CreatedAt" }
    ];

    /// <summary>
    /// Gets the credentials to display, with optional column-based sorting applied.
    /// </summary>
    private IEnumerable<ItemListEntry> DisplayedCredentials
    {
        get
        {
            // If user has explicitly clicked a column header to sort, apply that sorting
            if (UserHasClickedColumn)
            {
                return SortList(Credentials, SortColumn, CurrentSortDirection);
            }

            // Otherwise use the pre-sorted credentials passed from parent
            return Credentials;
        }
    }

    /// <summary>
    /// Gets the default sort column based on the sort order.
    /// </summary>
    private string GetDefaultSortColumn()
    {
        return SortOrder switch
        {
            CredentialSortOrder.Alphabetical => "Service",
            _ => "CreatedAt", // OldestFirst and NewestFirst
        };
    }

    /// <summary>
    /// Gets the default sort direction based on the sort order.
    /// </summary>
    private SortDirection GetDefaultSortDirection()
    {
        return SortOrder switch
        {
            CredentialSortOrder.NewestFirst => SortDirection.Descending,
            CredentialSortOrder.Alphabetical => SortDirection.Ascending,
            _ => SortDirection.Ascending, // OldestFirst (default)
        };
    }

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

        // Only reset if the SortOrder parameter has changed
        var newDefaultColumn = GetDefaultSortColumn();
        var newDefaultDirection = GetDefaultSortDirection();

        if (SortColumn != newDefaultColumn || (!UserHasClickedColumn && CurrentSortDirection != newDefaultDirection))
        {
            SortColumn = newDefaultColumn;
            CurrentSortDirection = newDefaultDirection;
            UserHasClickedColumn = false; // Reset user interaction state when parameters change
        }
    }

    /// <summary>
    /// Handles the sort changed event.
    /// </summary>
    /// <param name="sort">The sort event.</param>
    private void HandleSortChanged((string column, SortDirection direction) sort)
    {
        SortColumn = sort.column;
        CurrentSortDirection = sort.direction;
        UserHasClickedColumn = true;
        StateHasChanged();
    }

    /// <summary>
    /// Sorts the list of credentials.
    /// </summary>
    /// <param name="credentials">The list of credentials to sort.</param>
    /// <param name="sortColumn">The column to sort by.</param>
    /// <param name="sortDirection">The direction to sort by.</param>
    private static IEnumerable<ItemListEntry> SortList(List<ItemListEntry> credentials, string sortColumn, SortDirection sortDirection)
    {
        return sortColumn switch
        {
            "Service" => SortableTable.SortListByProperty(credentials, c => c.Service, sortDirection),
            "Username" => SortableTable.SortListByProperty(credentials, c => c.Username, sortDirection),
            "Email" => SortableTable.SortListByProperty(credentials, c => c.Email, sortDirection),
            "CreatedAt" => SortableTable.SortListByProperty(credentials, c => c.CreatedAt, sortDirection),
            _ => credentials
        };
    }

    /// <summary>
    /// Navigates to the credential details page.
    /// </summary>
    /// <param name="credentialId">The ID of the credential to navigate to.</param>
    private void NavigateToCredential(Guid credentialId)
    {
        NavigationManager.NavigateTo($"/items/{credentialId}");
    }
}
