@using BackOffice.Services.DiscountProduct
@using BackOffice.Services.DiscountCategory
@using Microsoft.AspNetCore.Components.Forms
@using Tizzani.MudBlazor.HtmlEditor
@using BackOffice.Common.BaseComponents
@using BackOffice.Pages.AutoComplete
@inject ISnackbar Snackbar

<MudDialog>
    <DialogContent>
        <MudForm @ref="_form" @bind-IsValid="@_isValid">
            <MudStack Spacing="3">
                <MudStack Justify="Justify.Center" AlignItems="AlignItems.Center">
                    @if (!string.IsNullOrWhiteSpace(_mainImagePreview))
                    {
                        <Image Src="@(_mainImagePreview)" Width="220" Height="140" ObjectPosition="ObjectPosition.Center" ObjectFit="ObjectFit.Cover" />
                    }
                    else if (!string.IsNullOrEmpty(Model.ImagePath))
                    {
                        <Image Src="@Model.ImagePath" Width="220" Height="140" ObjectPosition="ObjectPosition.Center" ObjectFit="ObjectFit.Cover" />
                    }
                    else
                    {
                        <MudPaper Class="d-flex align-center justify-center" Style="width:220px;height:140px;">
                            <MudText Typo="Typo.caption">تصویری انتخاب نشده است</MudText>
                        </MudPaper>
                    }

                    <MudFileUpload T="IBrowserFile" Accept="image/*" FilesChanged="OnMainImageSelected">
                        <ActivatorContent>
                            <MudButton HtmlTag="label"
                                       Variant="Variant.Filled"
                                       Color="Color.Primary"
                                       ButtonType="ButtonType.Button"
                                       StartIcon="@Icons.Material.Filled.Image"
                                      >
                                انتخاب تصویر اصلی
                            </MudButton>
                        </ActivatorContent>
                        <SelectedTemplate>
                            @if (context != null)
                            {
                                <MudText Class="mt-2" Typo="Typo.subtitle2">
                                    <MudTooltip Text="@context.Name" Inline="true">
                                        @context.Name
                                    </MudTooltip>
                                </MudText>
                            }
                            else
                            {
                                <MudText Class="mt-2" Typo="Typo.subtitle2">فایلی انتخاب نشده</MudText>
                            }
                        </SelectedTemplate>
                    </MudFileUpload>
                </MudStack>

                <MudStack Row="true" AlignItems="AlignItems.Center">
                    <MudItem xs="6">
                        <MudTextField T="string" @bind-Value="Model.Title" 
                                      Disabled="_loading" 
                                      Label="عنوان محصول *" 
                                      Required="true"
                                      RequiredError="عنوان الزامی است"
                                      Variant="Variant.Outlined" 
                                      Margin="Margin.Dense" />
                    </MudItem>
                    <MudItem xs="6">
                        <MudNumericField T="long" HideSpinButtons="true" 
                                         @bind-Value="Model.Price" 
                                         Format="N0" 
                                         Immediate="true"
                                         Disabled="_loading" 
                                         Label="قیمت (تومان) *" 
                                         Required="true"
                                         Variant="Variant.Outlined" 
                                         Margin="Margin.Dense" />
                    </MudItem>
                </MudStack>

                <MudStack Row="true" AlignItems="AlignItems.Center">
                    <MudItem xs="6">
                        <MudNumericField T="int" HideSpinButtons="true" 
                                         @bind-Value="Model.MaxDiscountPercent" 
                                         Disabled="_loading" 
                                         Label="حداکثر درصد تخفیف *" 
                                         Required="true"
                                         Min="0"
                                         Max="100"
                                         Variant="Variant.Outlined" 
                                         Margin="Margin.Dense" />
                    </MudItem>
                    <MudItem xs="6">
                        <MudNumericField T="int" HideSpinButtons="true" 
                                         @bind-Value="Model.SortOrder" 
                                         Disabled="_loading" 
                                         Label="ترتیب نمایش" 
                                         Min="0"
                                         Variant="Variant.Outlined" 
                                         Margin="Margin.Dense" />
                    </MudItem>
                </MudStack>

                <MudTextField T="string" @bind-Value="Model.ShortInformation" 
                              Disabled="_loading" 
                              Label="توضیح کوتاه" 
                              Variant="Variant.Outlined" 
                              Margin="Margin.Dense" />

                <MudHtmlEditor @bind-Html="Model.FullInformation" MinHeight="300px">
                    <MudHtmlToolbarOptions InsertImage="false" />
                </MudHtmlEditor>

                <MudStack Spacing="1">
                    <MudText Typo="Typo.subtitle2">دسته‌بندی‌ها</MudText>
                    <DiscountCategoryMultiSelectCombo @bind-SelectedIds="_selectedCategoryIds"
                                                      Label="انتخاب دسته‌بندی‌ها"
                                                      Disabled="_loading" />
                    @if (_selectedCategoryIds?.Count > 0)
                    {
                        <MudText Typo="Typo.caption">
                            تعداد دسته‌بندی‌های انتخاب‌شده: @_selectedCategoryIds.Count
                        </MudText>
                    }
                </MudStack>

                <MudStack Spacing="1">
                    <MudText Typo="Typo.subtitle2">تصویر بندانگشتی</MudText>
                    @if (!string.IsNullOrWhiteSpace(_thumbnailPreview))
                    {
                        <Image Src="@(_thumbnailPreview)" Width="120" Height="80" ObjectPosition="ObjectPosition.Center" ObjectFit="ObjectFit.Cover" />
                    }
                    else if (!string.IsNullOrEmpty(Model.ThumbnailPath))
                    {
                        <Image Src="@Model.ThumbnailPath" Width="120" Height="80" ObjectPosition="ObjectPosition.Center" ObjectFit="ObjectFit.Cover" />
                    }
                    <MudFileUpload T="IBrowserFile" Accept="image/*" FilesChanged="OnThumbnailSelected">
                        <ActivatorContent>
                            <MudButton HtmlTag="label"
                                       Variant="Variant.Outlined"
                                       Color="Color.Secondary"
                                       ButtonType="ButtonType.Button"
                                       StartIcon="@Icons.Material.Filled.Image"
                                      >
                                انتخاب تصویر بندانگشتی (اختیاری)
                            </MudButton>
                        </ActivatorContent>
                    </MudFileUpload>
                </MudStack>

                <MudSwitch T="bool" @bind-Value="Model.IsActive" 
                           Label="محصول فعال" 
                           Color="Color.Success" />
            </MudStack>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel" Disabled="_loading">انصراف</MudButton>
        <MudButton OnClick="Submit" 
                   Color="Color.Primary" 
                   Disabled="@(!_isValid || _loading)">ثبت</MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = null!;
    [Parameter] public ProductFormModel Model { get; set; } = new();
    [Parameter] public bool IsEditMode { get; set; }

    private MudForm? _form;
    private bool _isValid;
    private bool _loading;
    private IBrowserFile? _mainImageFile;
    private IBrowserFile? _thumbnailImageFile;
    private readonly long _maxAllowedSize = (1024 * 1024) * 5;
    private string? _mainImagePreview;
    private string? _thumbnailPreview;
    private byte[]? _mainImageBuffer;
    private byte[]? _thumbnailImageBuffer;
    private List<long> _selectedCategoryIds = new();

    protected override Task OnInitializedAsync()
    {
        if (Model.CategoryIds?.Any() == true)
        {
            _selectedCategoryIds = Model.CategoryIds;
        }
        return base.OnInitializedAsync();
    }

    private async Task OnMainImageSelected(IBrowserFile? file)
    {
        _mainImageFile = file;
        if (file != null)
        {
            using var ms = new MemoryStream();
            await file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            _mainImageBuffer = ms.ToArray();
            _mainImagePreview = $"data:{file.ContentType};base64," + Convert.ToBase64String(_mainImageBuffer);
            StateHasChanged();
        }
    }

    private async Task OnThumbnailSelected(IBrowserFile? file)
    {
        _thumbnailImageFile = file;
        if (file != null)
        {
            using var ms = new MemoryStream();
            await file.OpenReadStream(_maxAllowedSize).CopyToAsync(ms);
            _thumbnailImageBuffer = ms.ToArray();
            _thumbnailPreview = $"data:{file.ContentType};base64," + Convert.ToBase64String(_thumbnailImageBuffer);
            StateHasChanged();
        }
    }

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

        _loading = true;

        // Update CategoryIds from selected values
        Model.CategoryIds = _selectedCategoryIds.ToList();

        // Handle main image upload
        if (_mainImageFile != null && _mainImageBuffer != null)
        {
            Model.ImageFile = _mainImageBuffer;
            Model.ImageMime = _mainImageFile.ContentType;
            Model.ImageFileName = Path.GetFileNameWithoutExtension(_mainImageFile.Name);
        }

        // Handle thumbnail upload
        if (_thumbnailImageFile != null && _thumbnailImageBuffer != null)
        {
            Model.ThumbnailFile = _thumbnailImageBuffer;
            Model.ThumbnailMime = _thumbnailImageFile.ContentType;
            Model.ThumbnailFileName = Path.GetFileNameWithoutExtension(_thumbnailImageFile.Name);
        }

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

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

    public class ProductFormModel
    {
        public string Title { get; set; } = string.Empty;
        public string? ShortInformation { get; set; }
        public string? FullInformation { get; set; }
        public string? ImagePath { get; set; }
        public string? ThumbnailPath { get; set; }
        public long Price { get; set; }
        public int MaxDiscountPercent { get; set; }
        public int SortOrder { get; set; }
        public bool IsActive { get; set; } = true;
        public List<long>? CategoryIds { get; set; }
        
        // Image upload properties
        public byte[]? ImageFile { get; set; }
        public string? ImageMime { get; set; }
        public string? ImageFileName { get; set; }
        public byte[]? ThumbnailFile { get; set; }
        public string? ThumbnailMime { get; set; }
        public string? ThumbnailFileName { get; set; }
    }
}
