using BackOffice.Common.Utilities;
using BackOffice.Services.DiscountOrder;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;

namespace BackOffice.Pages.DiscountShop.Components;

public partial class OrderDetailsDialog
{
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = null!;
    [Inject] public IDiscountOrderService OrderService { get; set; } = default!;
    [Inject] private IJSRuntime JsRuntime { get; set; } = default!;

    [Parameter] public DiscountOrderDetailsDto Order { get; set; } = null!;

    private OrderStatus _newStatus;
    private string? _trackingCode;
    private string? _adminNotes;
    private bool _isSaving;
    private List<TimelineStep> _timelineSteps = new();

    private string? DisplayMobile =>
        !string.IsNullOrWhiteSpace(Order.UserMobile) ? Order.UserMobile : Order.Address?.Phone;

    protected override void OnInitialized()
    {
        _newStatus = Order.Status;
        _trackingCode = Order.TrackingCode;
        _adminNotes = Order.AdminNotes;
        BuildTimeline();
    }

    private void BuildTimeline()
    {
        var status = Order.Status;
        var steps = new List<TimelineStep>
        {
            new()
            {
                Title = "ثبت سفارش",
                State = status == OrderStatus.Pending ? StepState.Active : StepState.Completed,
                Icon = "1"
            },
            new()
            {
                Title = "پرداخت",
                State = status switch
                {
                    OrderStatus.Pending => StepState.Inactive,
                    OrderStatus.Paid => StepState.Active,
                    OrderStatus.Cancelled => StepState.Inactive,
                    _ => Order.PaymentCompleted ? StepState.Completed : StepState.Inactive
                },
                Icon = "2"
            },
            new()
            {
                Title = "آماده‌سازی",
                State = status switch
                {
                    OrderStatus.Processing => StepState.Active,
                    OrderStatus.Shipped or OrderStatus.Delivered => StepState.Completed,
                    _ => StepState.Inactive
                },
                Icon = "3"
            },
            new()
            {
                Title = "ارسال",
                State = status switch
                {
                    OrderStatus.Shipped => StepState.Active,
                    OrderStatus.Delivered => StepState.Completed,
                    _ => StepState.Inactive
                },
                Icon = "4"
            },
            new()
            {
                Title = "تحویل / مرجوعی",
                State = status switch
                {
                    OrderStatus.Delivered => StepState.Completed,
                    OrderStatus.Returned => StepState.Completed,
                    OrderStatus.Cancelled => StepState.Completed,
                    _ => StepState.Inactive
                },
                Icon = "5"
            }
        };

        _timelineSteps = steps;
    }

    private Color GetStepColor(StepState state)
    {
        return state switch
        {
            StepState.Completed => Color.Success,
            StepState.Active => Color.Info,
            _ => Color.Default
        };
    }

    private async Task SaveAsync()
    {
        _isSaving = true;
        StateHasChanged();

        try
        {
            await OrderService.UpdateStatusAsync(Order.Id, new UpdateOrderStatusDto
            {
                Status = _newStatus,
                TrackingCode = _trackingCode,
                AdminNotes = _adminNotes
            });

            Snackbar.Add("تغییرات سفارش با موفقیت ذخیره شد.", Severity.Success);
            MudDialog.Close(DialogResult.Ok(true));
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در ذخیره تغییرات: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSaving = false;
            StateHasChanged();
        }
    }

    private void Close() => MudDialog.Close();

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

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

    private string GetPaymentStatusIcon(int status) => status switch
    {
        1 => Icons.Material.Filled.CheckCircle,
        2 => Icons.Material.Filled.Cancel,
        3 => Icons.Material.Filled.Replay,
        _ => Icons.Material.Filled.Schedule
    };

    private async Task PrintInvoiceAsync()
    {
        var lines = Order.Items.Select(i => new OrderInvoicePrint.InvoiceLine
        {
            Title = i.ProductTitle,
            Quantity = i.Count,
            UnitPrice = i.UnitPrice,
            Discount = i.DiscountAmount,
            LineTotal = i.FinalPrice > 0 ? i.FinalPrice : i.UnitPrice * i.Count
        }).ToList();

        var mobile = !string.IsNullOrWhiteSpace(Order.UserMobile)
            ? Order.UserMobile
            : Order.Address?.Phone;

        var html = OrderInvoicePrint.BuildHtml(new OrderInvoicePrint.InvoiceModel
        {
            ShopTitle = "فروشگاه اعتباری — کارا بازار سلامت",
            OrderId = string.IsNullOrWhiteSpace(Order.OrderNumber) ? Order.Id.ToString() : Order.OrderNumber,
            CustomerName = Order.UserFullName,
            CustomerMobile = mobile,
            Address = Order.Address?.Address,
            PostalCode = Order.Address?.PostalCode,
            PaymentStatus = GetPaymentStatusText(Order.PaymentStatusValue),
            TransactionId = Order.TransactionId,
            TrackingCode = Order.TrackingCode,
            Created = Order.Created,
            Subtotal = lines.Sum(l => l.UnitPrice * l.Quantity),
            DiscountTotal = lines.Sum(l => l.Discount),
            CreditUsed = Order.DiscountBalanceUsed,
            GatewayAmount = Order.GatewayAmount,
            VatAmount = Order.VatAmount,
            TotalAmount = Order.TotalPrice,
            Lines = lines
        });

        await JsRuntime.InvokeVoidAsync("jsHtmlToPdf", html, $"فاکتور سفارش {Order.Id}");
    }

    private enum StepState
    {
        Inactive = 0,
        Active = 1,
        Completed = 2
    }

    private class TimelineStep
    {
        public string Title { get; set; } = string.Empty;
        public StepState State { get; set; }
        public string Icon { get; set; } = string.Empty;
    }
}
