using System.Text;
using BackOffice.Common.BaseComponents;
using BackOffice.Common.Utilities;
using BackOffice.Services.DiscountOrder;
using BackOffice.Pages.DiscountShop.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;
using DateTimeConverterCL;

namespace BackOffice.Pages.DiscountShop;

public partial class DiscountOrdersMainPage
{
    [Inject] public IDiscountOrderService DiscountOrderService { get; set; } = default!;
    [Inject] public IJSRuntime JsRuntime { get; set; } = default!;

    private MudDataGrid<DiscountOrderDto>? _dataGrid;
    private BasePageComponent _basePage = default!;
    private List<DiscountOrderDto> _orders = new();
    private bool _loading;

    // فیلترها - یکسان با فروشگاه عادی
    private long? _orderIdFilter;
    private long? _userIdFilter;
    private string? _userMobileFilter;
    private string? _trackingCodeFilter;
    private DateTime? _fromDateFilter;
    private DateTime? _toDateFilter;
    private int? _paymentStatusFilter;
    private OrderStatus? _statusFilter;

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

    private async Task LoadOrders()
    {
        _loading = true;
        try
        {
            var filter = new OrderFilterDto
            {
                UserId = _userIdFilter ?? _orderIdFilter, // orderId → search by userId too
                Status = _statusFilter,
                PaymentStatus = _paymentStatusFilter,
                UserMobile = _userMobileFilter,
                TrackingCode = _trackingCodeFilter,
                FromDate = _fromDateFilter,
                ToDate = _toDateFilter
            };

            var (orders, totalCount, totalPages) = await DiscountOrderService.GetOrdersAsync(filter);
            _orders = orders;
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری سفارشات: {ex.Message}", Severity.Error);
        }
        finally
        {
            _loading = false;
        }
    }

    private async Task OpenOrderDetails(long orderId)
    {
        try
        {
            var order = await DiscountOrderService.GetByIdAsync(orderId);
            if (order == null)
            {
                Snackbar.Add("سفارش یافت نشد", Severity.Error);
                return;
            }

            // تکمیل فیلدهای فاکتور از ردیف لیست (جزئیات API نام/موبایل/VAT ندارد)
            var listRow = _orders?.FirstOrDefault(o => o.Id == orderId);
            if (listRow != null)
            {
                order.UserFullName = listRow.UserFullName;
                order.UserMobile = listRow.UserMobile;
                order.VatAmount = listRow.VatAmount;
            }

            var parameters = new DialogParameters<OrderDetailsDialog> { { x => x.Order, order } };
            var options = new DialogOptions { CloseOnEscapeKey = true, MaxWidth = MaxWidth.Large, FullWidth = true };
            var dialog = await DialogService.ShowAsync<OrderDetailsDialog>("جزئیات سفارش", parameters, options);
            var result = await dialog.Result;

            if (result is { Canceled: false })
            {
                await LoadOrders();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در بارگذاری جزئیات: {ex.Message}", Severity.Error);
        }
    }

    private async Task OpenChangeStatusDialog(DiscountOrderDto order)
    {
        var parameters = new DialogParameters<ChangeOrderStatusDialog>
        {
            { x => x.OrderId, order.Id },
            { x => x.CurrentStatus, order.Status }
        };

        var options = new DialogOptions { CloseOnEscapeKey = true, MaxWidth = MaxWidth.Small, FullWidth = true };
        var dialog = await DialogService.ShowAsync<ChangeOrderStatusDialog>(
            "تغییر وضعیت سفارش", parameters, options);
        var result = await dialog.Result;

        if (result is { Canceled: false, Data: UpdateOrderStatusDto dto })
        {
            try
            {
                await DiscountOrderService.UpdateStatusAsync(order.Id, dto);
                Snackbar.Add("وضعیت سفارش با موفقیت تغییر یافت", Severity.Success);
                await LoadOrders();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در تغییر وضعیت: {ex.Message}", Severity.Error);
            }
        }
    }

    private async Task OnDelete(DiscountOrderDto model)
    {
        var options = new DialogOptions { CloseOnEscapeKey = true, MaxWidth = MaxWidth.Small };
        bool? result = await DialogService.ShowMessageBox(
            "اخطار",
            $"آیا از لغو سفارش شماره «{model.Id}» مطمئن هستید؟ این عملیات وضعیت سفارش را به «لغو شده» تغییر می‌دهد.",
            yesText: "لغو سفارش", cancelText: "انصراف",
            options: options);
        if (result == true)
        {
            try
            {
                await DiscountOrderService.UpdateStatusAsync(model.Id, new UpdateOrderStatusDto
                {
                    Status = OrderStatus.Cancelled,
                    AdminNotes = "لغو شده توسط ادمین"
                });
                Snackbar.Add("سفارش با موفقیت لغو شد.", Severity.Success);
                await LoadOrders();
            }
            catch (Exception ex)
            {
                Snackbar.Add($"خطا در لغو سفارش: {ex.Message}", Severity.Error);
            }
        }

        StateHasChanged();
    }

    public async Task OnFilterSubmit()
    {
        _basePage.IsFiltered = true;
        StateHasChanged();
        await LoadOrders();
    }

    public async Task OnFilterCleared()
    {
        _basePage.IsFiltered = false;
        StateHasChanged();
        _orderIdFilter = null;
        _userIdFilter = null;
        _userMobileFilter = null;
        _trackingCodeFilter = null;
        _fromDateFilter = null;
        _toDateFilter = null;
        _paymentStatusFilter = null;
        _statusFilter = null;
        await LoadOrders();
    }

    private Color GetStatusColor(OrderStatus status)
    {
        return status switch
        {
            OrderStatus.Pending => Color.Warning,
            OrderStatus.Paid => Color.Info,
            OrderStatus.Processing => Color.Primary,
            OrderStatus.Shipped => Color.Secondary,
            OrderStatus.Delivered => Color.Success,
            OrderStatus.Cancelled => Color.Dark,
            OrderStatus.ReadyForOfficePickup => Color.Primary,
            OrderStatus.Returned => Color.Error,
            _ => Color.Default
        };
    }

    private string GetStatusText(OrderStatus status)
    {
        return status switch
        {
            OrderStatus.Pending => "در انتظار ارسال",
            OrderStatus.Paid => "پرداخت شده",
            OrderStatus.Processing => "در حال آماده‌سازی",
            OrderStatus.Shipped => "ارسال شده",
            OrderStatus.Delivered => "تحویل داده شده",
            OrderStatus.Cancelled => "لغو شده",
            OrderStatus.ReadyForOfficePickup => "آماده تحویل در دفتر",
            OrderStatus.Returned => "مرجوع شده",
            _ => "نامشخص"
        };
    }

    private Color GetPaymentStatusColor(int status)
    {
        return status switch
        {
            0 => Color.Warning,  // Pending
            1 => Color.Success,  // Completed
            2 => Color.Error,    // Failed
            3 => Color.Info,     // Refunded
            _ => Color.Default
        };
    }

    private string GetPaymentStatusText(int status)
    {
        return status switch
        {
            0 => "در انتظار پرداخت",
            1 => "پرداخت شده",
            2 => "ناموفق",
            3 => "بازپرداخت شده",
            _ => "نامشخص"
        };
    }

    private async Task ExportToExcel()
    {
        if (_orders == null || !_orders.Any())
        {
            Snackbar.Add("داده‌ای برای خروجی وجود ندارد.", Severity.Info);
            return;
        }

        try
        {
            var headers = new[]
            {
                "شناسه", "نام مشتری", "موبایل", "مبلغ کل", "کیف پول اعتباری", "پرداخت درگاه",
                "تعداد آیتم", "وضعیت پرداخت", "وضعیت ارسال", "تاریخ پرداخت", "تاریخ ثبت", "آدرس"
            };

            var rows = _orders.Select(o => new object?[]
            {
                o.Id,
                CsvExportHelper.CustomerName(o.UserFullName, o.UserMobile, o.UserId),
                o.UserMobile ?? "",
                o.TotalPrice,
                o.DiscountBalanceUsed,
                o.GatewayAmount,
                o.ItemsCount,
                GetPaymentStatusText(o.PaymentStatusValue),
                GetStatusText(o.Status),
                o.PaymentDate?.MiladiToJalaliWithTime() ?? "-",
                o.Created?.MiladiToJalaliWithTime() ?? "-",
                o.ShippingAddress ?? "-"
            });

            var filename = $"discount-orders-{DateTime.Now:yyyyMMddHHmmss}.xls";
            await JsRuntime.InvokeVoidAsync("jsSaveAsFile", filename,
                CsvExportHelper.ToExcelXmlBase64("سفارش‌های اعتباری", headers, rows));
            Snackbar.Add("خروجی Excel آماده شد.", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در خروجی Excel: {ex.Message}", Severity.Error);
        }
    }
}
