@using Blazored.LocalStorage
@using BackOffice.Services.PublicMessage
@using MudBlazor
@using static BackOffice.Pages.PublicMessages.Components.MessageFormDialog

@inject ILocalStorageService LocalStorage

<MudDialog>
    <DialogContent>
        <MudStack Spacing="2">
            <MudText Typo="Typo.h6">قالب‌های آماده پیام</MudText>

            <MudAlert Severity="Severity.Info">
                قالب‌ها فقط در مرورگر فعلی ذخیره می‌شوند و روی سرور ذخیره نمی‌شوند.
            </MudAlert>

            <MudGrid>
                <MudItem xs="12" md="4">
                    <MudTextField @bind-Value="_newTemplateTitle"
                                  Label="عنوان قالب"
                                  Variant="Variant.Outlined" />
                </MudItem>
                <MudItem xs="12" md="4">
                    <MudSelect @bind-Value="_newTemplateType"
                               Label="نوع پیام"
                               Variant="Variant.Outlined">
                        <MudSelectItem T="MessageType" Value="@MessageType.Announcement">اطلاعیه</MudSelectItem>
                        <MudSelectItem T="MessageType" Value="@MessageType.News">خبر</MudSelectItem>
                        <MudSelectItem T="MessageType" Value="@MessageType.Alert">هشدار</MudSelectItem>
                        <MudSelectItem T="MessageType" Value="@MessageType.Promotion">تبلیغات</MudSelectItem>
                    </MudSelect>
                </MudItem>
                <MudItem xs="12" md="2">
                    <MudNumericField @bind-Value="_newTemplatePriority"
                                     Label="اولویت"
                                     Min="1"
                                     Max="5"
                                     Variant="Variant.Outlined" />
                </MudItem>
                <MudItem xs="12">
                    <MudTextField @bind-Value="_newTemplateContent"
                                  Label="متن قالب"
                                  Variant="Variant.Outlined"
                                  Lines="4" />
                </MudItem>
                <MudItem xs="12">
                    <MudButton Color="Color.Primary"
                               Variant="Variant.Filled"
                               OnClick="AddTemplate"
                               Disabled="string.IsNullOrWhiteSpace(_newTemplateTitle) || string.IsNullOrWhiteSpace(_newTemplateContent)">
                        افزودن قالب
                    </MudButton>
                </MudItem>
            </MudGrid>

            <MudDivider Class="my-2" />

            <MudDataGrid T="MessageTemplateModel"
                         Items="@_templates"
                         Hover="true"
                         Dense="true">
                <Columns>
                    <PropertyColumn Property="x => x.Title" Title="عنوان" />
                    <TemplateColumn Title="نوع">
                        <CellTemplate>
                            <MudChip T="string" Color="Color.Info" Size="Size.Small">
                                @GetTypeText(context.Item.Type)
                            </MudChip>
                        </CellTemplate>
                    </TemplateColumn>
                    <PropertyColumn Property="x => x.Priority" Title="اولویت" />
                    <TemplateColumn Title="پیش‌نمایش متن">
                        <CellTemplate>
                            <MudTooltip Text="@context.Item.Content">
                                <MudText Typo="Typo.caption">
                                    @(context.Item.Content.Length > 40
                                        ? context.Item.Content.Substring(0, 40) + "..."
                                        : context.Item.Content)
                                </MudText>
                            </MudTooltip>
                        </CellTemplate>
                    </TemplateColumn>
                    <TemplateColumn Title="عملیات">
                        <CellTemplate>
                            <MudStack Row="true" Spacing="1">
                                <MudTooltip Text="استفاده از این قالب">
                                    <MudIconButton Icon="@Icons.Material.Filled.ContentPaste"
                                                   Color="Color.Primary"
                                                   Size="Size.Small"
                                                   OnClick="@(() => UseTemplate(context.Item))" />
                                </MudTooltip>
                                <MudTooltip Text="حذف">
                                    <MudIconButton Icon="@Icons.Material.Filled.Delete"
                                                   Color="Color.Error"
                                                   Size="Size.Small"
                                                   OnClick="@(() => DeleteTemplate(context.Item))" />
                                </MudTooltip>
                            </MudStack>
                        </CellTemplate>
                    </TemplateColumn>
                </Columns>
            <NoRecordsContent>
                <MudAlert Severity="Severity.Info" Dense="true" Variant="Variant.Text" Class="my-4">موردی یافت نشد.</MudAlert>
            </NoRecordsContent>
            </MudDataGrid>
        </MudStack>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Close" Variant="Variant.Text">بستن</MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;
    [Parameter] public EventCallback<MessageFormModel> OnTemplateSelected { get; set; }

    private const string StorageKey = "PublicMessageTemplates";

    private readonly List<MessageTemplateModel> _templates = new();
    private string _newTemplateTitle = string.Empty;
    private string _newTemplateContent = string.Empty;
    private MessageType _newTemplateType = MessageType.Announcement;
    private int _newTemplatePriority = 1;

    protected override async Task OnInitializedAsync()
    {
        var stored = await LocalStorage.GetItemAsync<List<MessageTemplateModel>>(StorageKey);
        if (stored != null)
        {
            _templates.AddRange(stored);
        }
    }

    private async Task PersistAsync()
    {
        await LocalStorage.SetItemAsync(StorageKey, _templates);
    }

    private async Task AddTemplate()
    {
        var template = new MessageTemplateModel
        {
            Id = Guid.NewGuid(),
            Title = _newTemplateTitle.Trim(),
            Content = _newTemplateContent.Trim(),
            Type = _newTemplateType,
            Priority = _newTemplatePriority
        };

        _templates.Add(template);
        await PersistAsync();

        _newTemplateTitle = string.Empty;
        _newTemplateContent = string.Empty;
        _newTemplateType = MessageType.Announcement;
        _newTemplatePriority = 1;
    }

    private async Task DeleteTemplate(MessageTemplateModel template)
    {
        _templates.Remove(template);
        await PersistAsync();
    }

    private async Task UseTemplate(MessageTemplateModel template)
    {
        if (OnTemplateSelected.HasDelegate)
        {
            var model = new MessageFormModel
            {
                Title = template.Title,
                Content = template.Content,
                Type = template.Type,
                Priority = template.Priority
            };

            await OnTemplateSelected.InvokeAsync(model);
        }
    }

    private void Close()
    {
        MudDialog.Close();
    }

    private static string GetTypeText(MessageType type)
    {
        return type switch
        {
            MessageType.Announcement => "اطلاعیه",
            MessageType.News => "خبر",
            MessageType.Alert => "هشدار",
            MessageType.Promotion => "تبلیغات",
            _ => "نامشخص"
        };
    }

    public class MessageTemplateModel
    {
        public Guid Id { get; set; }
        public string Title { get; set; } = string.Empty;
        public string Content { get; set; } = string.Empty;
        public MessageType Type { get; set; } = MessageType.Announcement;
        public int Priority { get; set; } = 1;
    }
}

