@implements IDisposable

@*
 *                                dbMango
 *
 * Copyright 2025 Deutsche Bank AG
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *@
    
<th class="py-0 align-bottom @Class">
    <div class="align-items-bottom">
        @if (Sortable)
        {
            <button class="btn px-0 w-100 text-left @HeaderStyle" @onclick="@(SortAction)">@Name<span class="@GetSortStyle() d-inline" /></button>
        }
        else
        {
            <button class="btn px-0 w-100 text-left @HeaderStyle">@Name</button>
        }
        @if (TableControl is { Filterable: true } && Filterable && !string.IsNullOrEmpty(Field) && (FilterDropdownValues?.Count ?? 0) == 0)
        {
            <input class="form-control w-100 p-0 mb-1" @bind="FilterString" @bind:event="oninput" />
        }
        @if (TableControl is { Filterable: true } && Filterable && FilterDropdownValues?.Count > 0)
        {
            <div class="dropdown">
                <button class="btn btn-secondary dropdown-toggle mb-1" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    Choose
                </button>
                <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                    @foreach (var value in FilterDropdownValues)
                    {
                        if (value == DefaultCheckedValue)
                        {
                            <div class="dropdown-item">
                                <input type="checkbox" @onchange="@CheckboxClicked" checked id=@value name=@value value=@value>
                                <label for=@value>@value</label><br>
                            </div>
                        }
                        else
                        {
                            <div class="dropdown-item">
                                <input type="checkbox" @onchange="@CheckboxClicked" id=@value name=@value value=@value>
                                <label for=@value>@value</label><br>
                            </div>
                        }
                    }
                </div>
            </div>
        }
    </div>
</th>

@code
{
    [Inject]
    private IJSRuntime? _js { get; set; }

    [Parameter] public List<string>?                                             FilterDropdownValues { get; set; }
    [Parameter] public string?                                                   DefaultCheckedValue  { get; set; }
    [Parameter] public string                                                    Name                 { get; set; } = "Column";
    [Parameter] public string?                                                   Field                { get; set; }
    [Parameter] public string?                                                   Class                { get; set; }
    [Parameter] public RenderFragment<(dynamic Row, TableColumnControl Column)>? Template             { get; set; }
    [Parameter] public string?                                                   Format               { get; set; }
    [Parameter] public string                                                    NegativeValueClass   { get; set; } = "t-neg";
    [Parameter] public string                                                    ZeroValueClass       { get; set; } = "t-zero";
    [Parameter] public string                                                    PositiveValueClass   { get; set; } = "t-pos";
    [Parameter] public bool                                                      Sortable             { get; set; } = true;
    [Parameter] public bool                                                      Filterable           { get; set; } = true;
    [Parameter] public bool                                                      ExactMatch           { get; set; } 
    [Parameter] public bool                                                      ShowTotals           { get; set; } = true;
    [Parameter] public string                                                    HeaderStyle          { get; set; } = "";

    [Parameter]
    public string FilterString
    {
        get;
        set
        {
            if (field == value)
                return;
            field = value;
            FilterChanged(value.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList());
        }
    } = string.Empty;

    [CascadingParameter]
    internal TableControl? TableControl { get; set; }

    public void SetFilter(string filterString)
    {
        FilterString = filterString;
        FilterChanged(FilterString.Split(",", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList());
    }

    protected override void OnInitialized()
    {
        TableControl?.AddColumn(this);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender && !string.IsNullOrWhiteSpace(DefaultCheckedValue))
        {
            if (_js == null)
                throw new ApplicationException("JS Runtime must be injected");

            var values = await _js.InvokeAsync<string>("DashboardUtils.CheckBox");
            if (!string.IsNullOrEmpty(values))
            {
                FilterChanged(values.Split(",").Where(v => !string.IsNullOrEmpty(v)).Select(x =>
                {
                    x = x.Trim();
                    if (x.Equals("Blanks")) return "";
                    return x;
                }).ToList());
            }
        }
    }

    public async Task CheckboxClicked()
    {
        var values = await _js!.InvokeAsync<string>("DashboardUtils.CheckBox");
        FilterChanged(values
            .Split(",")
            .Where(v => !string.IsNullOrEmpty(v))
            .Select(x => x.Trim().Equals("Blanks") ? "" : x)
            .ToList()
            );

    }

    public void Dispose()
    {
        TableControl?.RemoveColumn(this);
    }

    protected string GetSortStyle()
    {
        if (string.IsNullOrEmpty(Field) || TableControl?.CurrentSortColumn != Field)
        {
            return string.Empty;
        }

        const string style = "ui-icon-font ui-icon-sm ";
        return style + TableControl.SortMode switch
        {
            TableControl.SortModeType.NoSort             => "",
            TableControl.SortModeType.Ascending          => "icon-caret-up-sm" ,
            TableControl.SortModeType.Descending         => "icon-caret-down-sm",
            TableControl.SortModeType.AscendingAbsolute  => "icon-caret-up-sm" ,
            TableControl.SortModeType.DescendingAbsolute => "icon-caret-down-sm",
            _ => throw new ArgumentOutOfRangeException()
        };
    }

    private void SortAction()
    {
        if (!string.IsNullOrEmpty(Field))
        {
            TableControl?.SetColumnSort(Field);
        }
    }

    private void FilterChanged(List<string> filterValue)
    {
        if (Field == null || TableControl == null)
            return;
        var task = TableControl.SetColumnFilter(Field, filterValue, ExactMatch);
        task.Wait();
    }
}
