@namespace Radzen.Blazor
@using Radzen.Blazor
@using Radzen.Blazor.Spreadsheet
@using Radzen.Blazor.Spreadsheet.Tools
@using Radzen.Documents.Spreadsheet
@inject DialogService DialogService
@inherits RadzenSpreadsheetToolBase

<RadzenSplitButton Click=@OnClickAsync Icon="format_color_fill" Text=@(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_Conditional)) ?? "Conditional") Disabled=@IsDisabled Variant="Variant.Outlined" ButtonStyle="ButtonStyle.Base" Size="ButtonSize.Small">
    <ChildContent>
        <RadzenSplitButtonItem Text=@(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_GreaterThanMenu)) ?? "Greater Than...") Value="greater" />
        <RadzenSplitButtonItem Text=@(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_LessThanMenu)) ?? "Less Than...") Value="less" />
        <RadzenSplitButtonItem Text=@(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_BetweenMenu)) ?? "Between...") Value="between" />
        <RadzenSplitButtonItem Text=@(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_EqualToMenu)) ?? "Equal To...") Value="equal" />
        <RadzenSplitButtonItem Text=@(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_TextContainsMenu)) ?? "Text Contains...") Value="text" />
    </ChildContent>
</RadzenSplitButton>

@code {
    protected override SpreadsheetFeature? Feature => SpreadsheetFeature.ConditionalFormatting;

    private async Task OnClickAsync(RadzenSplitButtonItem? item)
    {
        if (Worksheet is null || Worksheet.Selection.Cell == CellRef.Invalid)
        {
            return;
        }

        var ruleType = item?.Value switch
        {
            "less" => ConditionalFormatRuleType.LessThan,
            "between" => ConditionalFormatRuleType.Between,
            "equal" => ConditionalFormatRuleType.EqualTo,
            "text" => ConditionalFormatRuleType.TextContains,
            _ => ConditionalFormatRuleType.GreaterThan
        };

        var result = await DialogService.OpenAsync<ConditionalFormatDialog>(Spreadsheet?.Localize(nameof(RadzenStrings.Spreadsheet_ConditionalFormattingTitle)) ?? "Conditional Formatting",
            new Dictionary<string, object?>
            {
                { "RuleType", ruleType }
            });

        if (result is ConditionalFormatBase rule && Spreadsheet is not null)
        {
            var command = new ConditionalFormatCommand(Worksheet, Worksheet.Selection.Range, rule);
            await Spreadsheet.ExecuteAsync(command);
        }
    }
}
