using BackOffice.Services.Blog;
using BackOffice.Pages.Blog.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using MudBlazor;

namespace BackOffice.Pages.Blog;

public partial class BlogPostManagementPage
{
    private MudDataGrid<BlogPostListItemDto> _grid = default!;
    private string? _search;
    private int? _statusFilter;
    private long? _categoryFilter;
    private List<BlogCategoryItemDto> _categories = new();

    protected override async Task OnInitializedAsync()
    {
        _categories = await BlogCategoryService.GetActiveAsync();
    }

    private async Task<GridData<BlogPostListItemDto>> LoadServerData(GridState<BlogPostListItemDto> state)
    {
        var filter = new BlogPostFilterDto
        {
            PageNumber = state.Page + 1,
            PageSize = state.PageSize,
            SearchTerm = _search,
            Status = _statusFilter,
            CategoryId = _categoryFilter
        };

        var result = await BlogPostService.GetAllAsync(filter);

        return new GridData<BlogPostListItemDto>
        {
            Items = result.Items,
            TotalItems = result.TotalCount
        };
    }

    private async Task ReloadAsync()
    {
        if (_grid != null)
        {
            await _grid.ReloadServerData();
        }
    }

    private void OnSearchKeyDown(KeyboardEventArgs args)
    {
        if (args.Key == "Enter")
        {
            _ = ReloadAsync();
        }
    }

    private static Color GetStatusColor(int status) => status switch
    {
        0 => Color.Default,   // Draft
        1 => Color.Success,   // Published
        2 => Color.Warning,   // Archived
        _ => Color.Default
    };

    private async Task CreatePost()
    {
        var parameters = new DialogParameters<BlogPostEditDialog>
        {
            { nameof(BlogPostEditDialog.Model), new BlogPostEditDto() },
            { nameof(BlogPostEditDialog.IsEditMode), false },
            { nameof(BlogPostEditDialog.Categories), _categories }
        };

        var dialog = await DialogService.ShowAsync<BlogPostEditDialog>("ایجاد پست جدید", parameters,
            new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Large, FullWidth = true });

        var result = await dialog.Result;
        if (!result.Canceled)
        {
            Snackbar.Add("پست با موفقیت ایجاد شد", Severity.Success);
            await ReloadAsync();
        }
    }

    private async Task EditPost(BlogPostListItemDto item)
    {
        var details = await BlogPostService.GetByIdAsync(item.Id);
        if (details == null)
        {
            Snackbar.Add("خطا در دریافت اطلاعات پست", Severity.Error);
            return;
        }

        var dto = new BlogPostEditDto
        {
            Title = details.Title,
            Slug = details.Slug,
            Summary = details.Summary,
            HtmlContent = details.HtmlContent,
            FeaturedImagePath = details.FeaturedImagePath,
            FeaturedImageThumbnailPath = details.FeaturedImageThumbnailPath,
            CategoryIds = details.Categories.Select(c => c.Id).ToList(),
            TagIds = details.Tags.Select(t => t.Id).ToList(),
            IsFeatured = details.IsFeatured,
            SortOrder = details.SortOrder
        };

        var parameters = new DialogParameters<BlogPostEditDialog>
        {
            { nameof(BlogPostEditDialog.Model), dto },
            { nameof(BlogPostEditDialog.PostId), item.Id },
            { nameof(BlogPostEditDialog.IsEditMode), true },
            { nameof(BlogPostEditDialog.Categories), _categories }
        };

        var dialog = await DialogService.ShowAsync<BlogPostEditDialog>("ویرایش پست", parameters,
            new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Large, FullWidth = true });

        var result = await dialog.Result;
        if (!result.Canceled)
        {
            Snackbar.Add("پست با موفقیت به‌روزرسانی شد", Severity.Success);
            await ReloadAsync();
        }
    }

    private async Task PublishPost(BlogPostListItemDto item)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "انتشار پست",
            $"آیا از انتشار پست «{item.Title}» مطمئن هستید؟",
            yesText: "انتشار",
            cancelText: "لغو");

        if (confirmed == true)
        {
            var result = await BlogPostService.PublishAsync(item.Id);
            if (result.Success)
            {
                Snackbar.Add("پست با موفقیت منتشر شد", Severity.Success);
            }
            else
            {
                Snackbar.Add(result.Message, Severity.Error);
            }
            await ReloadAsync();
        }
    }

    private async Task ArchivePost(BlogPostListItemDto item)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "آرشیو پست",
            $"آیا از آرشیو کردن پست «{item.Title}» مطمئن هستید؟",
            yesText: "آرشیو",
            cancelText: "لغو");

        if (confirmed == true)
        {
            var result = await BlogPostService.ArchiveAsync(item.Id);
            if (result.Success)
            {
                Snackbar.Add("پست آرشیو شد", Severity.Success);
            }
            else
            {
                Snackbar.Add(result.Message, Severity.Error);
            }
            await ReloadAsync();
        }
    }

    private async Task DeletePost(BlogPostListItemDto item)
    {
        var confirmed = await DialogService.ShowMessageBox(
            "حذف پست",
            $"آیا از حذف پست «{item.Title}» مطمئن هستید؟",
            yesText: "حذف",
            cancelText: "لغو");

        if (confirmed == true)
        {
            await BlogPostService.DeleteAsync(item.Id);
            Snackbar.Add("پست حذف شد", Severity.Success);
            await ReloadAsync();
        }
    }
}
