@using BackOffice.Services.DiscountCategory
@inject ISnackbar Snackbar

<MudDialog>
    <DialogContent>
        <MudForm @ref="_form" @bind-IsValid="@_isValid">
            <MudGrid>
                <MudItem xs="12" sm="6">
                    <MudTextField @bind-Value="Model.Name" 
                                  Label="نام (slug) *" 
                                  Required="true"
                                  RequiredError="نام الزامی است"
                                  Variant="Variant.Outlined" />
                </MudItem>

                <MudItem xs="12" sm="6">
                    <MudTextField @bind-Value="Model.Title" 
                                  Label="عنوان دسته‌بندی *" 
                                  Required="true"
                                  RequiredError="عنوان الزامی است"
                                  Variant="Variant.Outlined" />
                </MudItem>

                <MudItem xs="12">
                    <MudTextField @bind-Value="Model.Description" 
                                  Label="توضیحات" 
                                  Lines="3"
                                  Variant="Variant.Outlined" />
                </MudItem>

                <MudItem xs="12">
                    <MudTextField @bind-Value="Model.ImagePath" 
                                  Label="آدرس تصویر" 
                                  Variant="Variant.Outlined" />
                </MudItem>

                <MudItem xs="12" sm="6">
                    <MudSelect @bind-Value="Model.ParentCategoryId" 
                               Label="دسته‌بندی والد" 
                               Variant="Variant.Outlined"
                               T="long?"
                               Clearable="true"
                               HelperText="برای دسته اصلی خالی بگذارید">
                        @foreach (var category in _availableParents)
                        {
                            <MudSelectItem T="long?" Value="@((long?)category.Id)">@GetCategoryPath(category)</MudSelectItem>
                        }
                    </MudSelect>
                </MudItem>

                <MudItem xs="12" sm="6">
                    <MudNumericField @bind-Value="Model.SortOrder" 
                                     Label="ترتیب نمایش" 
                                     Min="0"
                                     Variant="Variant.Outlined"
                                     HelperText="عدد کمتر = اولویت بالاتر" />
                </MudItem>

                <MudItem xs="12">
                    <MudSwitch T="bool" @bind-Value="Model.IsActive" 
                               Label="دسته‌بندی فعال" 
                               Color="Color.Success" />
                </MudItem>
            </MudGrid>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel" Variant="Variant.Text">انصراف</MudButton>
        <MudButton OnClick="Submit" 
                   Variant="Variant.Filled" 
                   Color="Color.Primary" 
                   Disabled="@(!_isValid || _loading)">
            @if (_loading)
            {
                <MudProgressCircular Size="Size.Small" Indeterminate="true" />
            }
            else
            {
                <text>@(IsEditMode ? "ذخیره تغییرات" : "ایجاد دسته‌بندی")</text>
            }
        </MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = null!;
    [Parameter] public CategoryFormModel Model { get; set; } = new();
    [Parameter] public bool IsEditMode { get; set; }
    [Parameter] public long? ExcludeCategoryId { get; set; }
    [Inject] private IDiscountCategoryService CategoryService { get; set; } = null!;

    private MudForm? _form;
    private bool _isValid;
    private bool _loading;
    private List<DiscountCategoryDto> _availableParents = new();

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

    private async Task LoadCategories()
    {
        try
        {
            var tree = await CategoryService.GetCategoriesAsync(isActive: null);
            var flat = FlattenCategories(tree);
            
            // در حالت Edit، دسته جاری و فرزندانش را نمایش نده
            if (ExcludeCategoryId.HasValue)
            {
                _availableParents = flat.Where(c => c.Id != ExcludeCategoryId.Value).ToList();
            }
            else
            {
                _availableParents = flat;
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری دسته‌بندی‌ها: {ex.Message}", Severity.Error);
        }
    }

    private List<DiscountCategoryDto> FlattenCategories(List<DiscountCategoryDto> categories, string prefix = "")
    {
        var result = new List<DiscountCategoryDto>();
        foreach (var category in categories)
        {
            var catCopy = new DiscountCategoryDto
            {
                Id = category.Id,
                Title = prefix + category.Title,
                ParentCategoryId = category.ParentCategoryId
            };
            result.Add(catCopy);
            
            if (category.Children.Any())
            {
                result.AddRange(FlattenCategories(category.Children.ToList(), prefix + "  "));
            }
        }
        return result;
    }

    private string GetCategoryPath(DiscountCategoryDto category)
    {
        return category.Title;
    }

    private async Task Submit()
    {
        if (_form != null)
        {
            await _form.Validate();
            if (!_isValid) return;
        }

        _loading = true;
        MudDialog.Close(DialogResult.Ok(Model));
        _loading = false;
    }

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

    public class CategoryFormModel
    {
        public string Name { get; set; } = string.Empty;
        public string Title { get; set; } = string.Empty;
        public string? Description { get; set; }
        public string? ImagePath { get; set; }
        public long? ParentCategoryId { get; set; }
        public int SortOrder { get; set; } = 0;
        public bool IsActive { get; set; } = true;
    }
}
