using BackOffice.Common.BaseComponents;
using BackOffice.Common.Utilities;
using BackOffice.Services.DiscountCategory;
using BackOffice.Pages.DiscountShop.Components;
using static BackOffice.Pages.DiscountShop.Components.CategoryFormDialog;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace BackOffice.Pages.DiscountShop;

public partial class DiscountCategoriesMainPage
{
    [Inject] public IDiscountCategoryService DiscountCategoryService { get; set; } = default!;

    private List<DiscountCategoryDto> _allCategories = new();
    private List<DiscountCategoryDto> _filteredCategories = new();
    private List<TreeNodeModel> _treeNodes = new();
    private BasePageComponent _basePage = default!;
    private bool _loading;
    private string? _searchQuery;
    private long? _selectedParentId;

    protected override async Task OnInitializedAsync()
    {
        await LoadCategories();
    }

    private async Task LoadCategories()
    {
        _loading = true;
        try
        {
            var rootCategories = await DiscountCategoryService.GetCategoriesAsync();
            _allCategories = FlattenCategoriesWithDepth(rootCategories, 0);
            BuildTreeNodes(rootCategories);
            FilterCategories();
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری دسته‌بندی‌ها: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private void BuildTreeNodes(List<DiscountCategoryDto> categories, int depth = 0)
    {
        _treeNodes.Clear();
        BuildTreeNodesRecursive(categories, depth);
    }

    private void BuildTreeNodesRecursive(List<DiscountCategoryDto> categories, int depth)
    {
        foreach (var cat in categories.OrderBy(c => c.SortOrder))
        {
            _treeNodes.Add(new TreeNodeModel
            {
                Id = cat.Id,
                Title = cat.Title,
                Depth = depth,
                HasChildren = cat.Children.Any()
            });
            if (cat.Children.Any())
            {
                BuildTreeNodesRecursive(cat.Children, depth + 1);
            }
        }
    }

    private List<DiscountCategoryDto> FlattenCategoriesWithDepth(List<DiscountCategoryDto> categories, int depth)
    {
        var result = new List<DiscountCategoryDto>();
        foreach (var category in categories.OrderBy(c => c.SortOrder))
        {
            result.Add(category);
            if (category.Children.Any())
            {
                result.AddRange(FlattenCategoriesWithDepth(category.Children, depth + 1));
            }
        }
        return result;
    }

    private void OnTreeNodeSelected(long? parentId)
    {
        _selectedParentId = parentId;
        FilterCategories();
        StateHasChanged();
    }

    private void FilterCategories()
    {
        var items = _allCategories.AsEnumerable();

        if (_selectedParentId.HasValue)
        {
            items = items.Where(c =>
                c.Id == _selectedParentId.Value ||
                c.ParentCategoryId == _selectedParentId.Value);
        }

        if (!string.IsNullOrWhiteSpace(_searchQuery))
        {
            var query = _searchQuery.ToLower();
            items = items.Where(c =>
                c.Title.ToLower().Contains(query) ||
                c.Name.ToLower().Contains(query) ||
                (c.Description?.ToLower().Contains(query) ?? false));
        }

        _filteredCategories = items.ToList();
    }

    private async Task OnFilterSubmit()
    {
        _basePage.IsFiltered = true;
        FilterCategories();
        StateHasChanged();
    }

    private async Task OnFilterCleared()
    {
        _basePage.IsFiltered = false;
        _searchQuery = null;
        _selectedParentId = null;
        FilterCategories();
        StateHasChanged();
    }

    private async Task OpenCreateDialog(long? parentId = null)
    {
        var model = new CategoryFormModel { ParentCategoryId = parentId };
        var parameters = new DialogParameters<CategoryFormDialog>
        {
            { x => x.Model, model },
            { x => x.IsEditMode, false },
            { x => x.ExcludeCategoryId, (long?)null }
        };

        var options = new DialogOptions { MaxWidth = MaxWidth.Small, FullWidth = true };
        var dialog = await DialogService.ShowAsync<CategoryFormDialog>(
            parentId.HasValue ? "ایجاد زیردسته" : "ایجاد دسته‌بندی جدید",
            parameters,
            options);
        var result = await dialog.Result;

        if (result is { Canceled: false, Data: CategoryFormModel formData })
        {
            try
            {
                var dto = new CreateDiscountCategoryDto
                {
                    ParentCategoryId = formData.ParentCategoryId,
                    Name = formData.Name,
                    Title = formData.Title,
                    Description = formData.Description,
                    ImagePath = formData.ImagePath,
                    SortOrder = formData.SortOrder,
                    IsActive = formData.IsActive
                };

                await DiscountCategoryService.CreateAsync(dto);
                Snackbar.Add("دسته‌بندی با موفقیت ایجاد شد", Severity.Success);
                await LoadCategories();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در ایجاد دسته‌بندی: {ex.Message}", Severity.Error);
            }
        }
    }

    private async Task OpenEditDialog(long categoryId)
    {
        try
        {
            var category = await DiscountCategoryService.GetByIdAsync(categoryId);
            if (category == null)
            {
                Snackbar.Add("دسته‌بندی یافت نشد", Severity.Error);
                return;
            }

            var model = new CategoryFormModel
            {
                ParentCategoryId = category.ParentCategoryId,
                Name = category.Name,
                Title = category.Title,
                Description = category.Description,
                ImagePath = category.ImagePath,
                SortOrder = category.SortOrder,
                IsActive = category.IsActive
            };

            var parameters = new DialogParameters<CategoryFormDialog>
            {
                { x => x.Model, model },
                { x => x.IsEditMode, true },
                { x => x.ExcludeCategoryId, categoryId }
            };

            var options = new DialogOptions { MaxWidth = MaxWidth.Small, FullWidth = true };
            var dialog = await DialogService.ShowAsync<CategoryFormDialog>("ویرایش دسته‌بندی", parameters, options);
            var result = await dialog.Result;

            if (result is { Canceled: false, Data: CategoryFormModel formData })
            {
                var dto = new UpdateDiscountCategoryDto
                {
                    ParentCategoryId = formData.ParentCategoryId,
                    Name = formData.Name,
                    Title = formData.Title,
                    Description = formData.Description,
                    ImagePath = formData.ImagePath,
                    SortOrder = formData.SortOrder,
                    IsActive = formData.IsActive
                };

                await DiscountCategoryService.UpdateAsync(categoryId, dto);
                Snackbar.Add("دسته‌بندی با موفقیت ویرایش شد", Severity.Success);
                await LoadCategories();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در ویرایش دسته‌بندی: {ex.Message}", Severity.Error);
        }
    }

    private async Task DeleteCategory(long categoryId)
    {
        var category = _allCategories.FirstOrDefault(c => c.Id == categoryId);
        if (category?.Children.Any() == true)
        {
            Snackbar.Add("ابتدا زیردسته‌های این دسته‌بندی را حذف کنید", Severity.Warning);
            return;
        }

        var options = new DialogOptions { CloseOnEscapeKey = true, MaxWidth = MaxWidth.Small };
        bool? result = await DialogService.ShowMessageBox(
            "اخطار",
            $"آیا از حذف دسته‌بندی «{category?.Title}» مطمئن هستید؟",
            yesText: "حذف", cancelText: "لغو",
            options: options);

        if (result == true)
        {
            try
            {
                await DiscountCategoryService.DeleteAsync(categoryId);
                Snackbar.Add("دسته‌بندی با موفقیت حذف شد", Severity.Success);
                await LoadCategories();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در حذف دسته‌بندی: {ex.Message}", Severity.Error);
            }
        }
    }

    private class TreeNodeModel
    {
        public long Id { get; set; }
        public string Title { get; set; } = string.Empty;
        public int Depth { get; set; }
        public bool HasChildren { get; set; }
    }

    public void OpenCategoryProducts(DiscountCategoryDto model)
    {
        Navigation.NavigateTo($"{RouteConstance.CategoryProducts}{model.Id}");
    }
}
