using System.Text;
using BackOffice.Common.BaseComponents;
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;
            }

            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.Error,
            OrderStatus.Returned => Color.Dark,
            _ => Color.Default
        };
    }

    private string GetStatusText(OrderStatus status)
    {
        return status switch
        {
            OrderStatus.Pending => "در انتظار ارسال",
            OrderStatus.Paid => "پرداخت شده",
            OrderStatus.Processing => "در حال آماده‌سازی",
            OrderStatus.Shipped => "ارسال شده",
            OrderStatus.Delivered => "تحویل داده شده",
            OrderStatus.Cancelled => "لغو شده",
            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 sb = new StringBuilder();
            sb.AppendLine("شناسه,نام کاربر,موبایل,مبلغ کل,کیف پول اعتباری,پرداخت درگاه,تعداد آیتم,وضعیت پرداخت,وضعیت ارسال,تاریخ پرداخت,تاریخ ثبت,آدرس");

            foreach (var o in _orders)
            {
                sb.AppendLine(string.Join(",",
                    o.Id,
                    EscapeCsv(o.UserFullName),
                    EscapeCsv(o.UserMobile),
                    o.TotalPrice.ToString("N0"),
                    o.DiscountBalanceUsed.ToString("N0"),
                    o.GatewayAmount.ToString("N0"),
                    o.ItemsCount,
                    EscapeCsv(GetPaymentStatusText(o.PaymentStatusValue)),
                    EscapeCsv(GetStatusText(o.Status)),
                    o.PaymentDate?.MiladiToJalaliWithTime() ?? "-",
                    o.Created?.MiladiToJalaliWithTime() ?? "-",
                    EscapeCsv(o.ShippingAddress ?? "-")));
            }

            var bytes = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(sb.ToString())).ToArray();
            var base64 = Convert.ToBase64String(bytes);
            var filename = $"discount-orders-{DateTime.Now:yyyyMMddHHmmss}.csv";

            await JsRuntime.InvokeVoidAsync("jsSaveAsFile", filename, base64);
            Snackbar.Add("خروجی Excel (CSV) آماده شد.", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در خروجی Excel: {ex.Message}", Severity.Error);
        }
    }

    private static string EscapeCsv(string value)
    {
        if (string.IsNullOrEmpty(value)) return "";
        if (value.Contains(',') || value.Contains('"') || value.Contains('\n'))
            return $"\"{value.Replace("\"", "\"\"")}\"";
        return value;
    }
}
