using BackOffice.Common.Utilities;
using CMSMicroservice.Protobuf.Protos;
using CMSMicroservice.Protobuf.Protos.UserOrder;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using MudBlazor;

namespace BackOffice.Pages.UserOrder.Components;

public partial class UserOrderDetailsDialog
{
    [CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;
    [Inject] public UserOrderContract.UserOrderContractClient UserOrderContract { get; set; } = default!;
    [Inject] private IJSRuntime JsRuntime { get; set; } = default!;

    [Parameter] public long OrderId { get; set; }

    private GetUserOrderResponse? _model;
    private bool _isLoading;
    private int _deliveryStatusValue;
    private string? _trackingCode;
    private string? _deliveryDescription;
    private List<TimelineStep> _timelineSteps = new();

    protected override async Task OnInitializedAsync()
    {
        _isLoading = true;
        try
        {
            _model = await UserOrderContract.GetUserOrderAsync(new GetUserOrderRequest
            {
                Id = OrderId
            });

            if (_model is not null)
            {
                _deliveryStatusValue = _model.DeliveryStatus.GetHashCode();
                _trackingCode = _model.TrackingCode;
                _deliveryDescription = _model.DeliveryDescription;

                BuildTimeline();
            }
        }
        catch
        {
            _model = null;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private Color GetDeliveryStatusColor(int status)
    {
        return status switch
        {
            1 => Color.Warning, // Pending
            2 => Color.Info,    // InTransit
            3 => Color.Success, // Delivered
            4 => Color.Error,   // Returned
            5 => Color.Dark,    // Cancelled
            6 => Color.Primary, // ReadyForOfficePickup
            _ => Color.Default  // None / Unknown
        };
    }

    private string GetDeliveryStatusText(int status)
    {
        return status switch
        {
            1 => "در انتظار ارسال",
            2 => "تحویل پست",
            3 => "تحویل به مشتری",
            4 => "مرجوع شده",
            5 => "لغو شده",
            6 => "آماده تحویل در دفتر",
            _ => "بدون ارسال / نامشخص"
        };
    }

    private string GetPaymentMethodText(int method)
    {
        return method switch
        {
            1 => "کیف پول",
            _ => "درگاه پرداخت"
        };
    }

    private void BuildTimeline()
    {
        if (_model is null)
        {
            _timelineSteps = new List<TimelineStep>();
            return;
        }

        var steps = new List<TimelineStep>
        {
            new()
            {
                Title = "ثبت سفارش",
                // PaymentStatus doesn't have None - using DeliveryStatus only for initial state
                State = (int)_model.DeliveryStatus == 0 ? StepState.Active : StepState.Completed,
                Icon = "1"
            },
            new()
            {
                Title = "پرداخت",
                State = _model.PaymentStatus switch
                {
                    PaymentStatus.Success => StepState.Completed,
                    PaymentStatus.Pending => StepState.Active,
                    _ => StepState.Inactive
                },
                Icon = "2"
            },
            new()
            {
                Title = "ارسال",
                State = _model.DeliveryStatus switch
                {
                    DeliveryStatus.Pending => StepState.Active,
                    DeliveryStatus.InTransit => StepState.Active,
                    DeliveryStatus.Delivered => StepState.Completed,
                    DeliveryStatus.Returned => StepState.Completed,
                    _ => StepState.Inactive
                },
                Icon = "3"
            },
            new()
            {
                Title = "تحویل / مرجوعی",
                State = _model.DeliveryStatus switch
                {
                    DeliveryStatus.Delivered => StepState.Completed,
                    DeliveryStatus.Returned => StepState.Completed,
                    _ => StepState.Inactive
                },
                Icon = "4"
            }
        };

        _timelineSteps = steps;
    }

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

    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;
    }

    private async Task SaveAsync()
    {
        if (_model is null)
            return;

        await UserOrderContract.UpdateUserOrderAsync(new UpdateUserOrderRequest
        {
            Id = _model.Id,
            DeliveryStatus = (DeliveryStatus)_deliveryStatusValue,
            TrackingCode = _trackingCode ?? string.Empty,
            DeliveryDescription = _deliveryDescription ?? string.Empty
        });

        MudDialog.Close(DialogResult.Ok(true));
    }

    private async Task PrintInvoiceAsync()
    {
        if (_model is null) return;

        var vat = _model.VatInfo;
        var lines = _model.FactorDetails.Select(f =>
        {
            var unit = f.UnitPrice ?? 0;
            var count = f.Count ?? 0;
            var discountUnit = f.UnitDiscountPrice ?? 0;
            var lineDiscount = Math.Max(0, (unit - discountUnit) * count);
            var lineTotal = discountUnit > 0 ? discountUnit * count : unit * count;
            return new OrderInvoicePrint.InvoiceLine
            {
                Title = f.ProductTitle ?? "",
                Quantity = count,
                UnitPrice = unit,
                Discount = lineDiscount,
                LineTotal = lineTotal
            };
        }).ToList();

        var subtotal = lines.Sum(l => l.UnitPrice * l.Quantity);
        var discountTotal = lines.Sum(l => l.Discount);
        var total = vat is { TotalAmount: > 0 } ? vat.TotalAmount : _model.Amount;

        var html = OrderInvoicePrint.BuildHtml(new OrderInvoicePrint.InvoiceModel
        {
            ShopTitle = "فروشگاه عادی — کارا بازار سلامت",
            OrderId = _model.Id.ToString(),
            CustomerName = _model.UserFullName,
            CustomerMobile = _model.UserMobile,
            CustomerNationalCode = _model.UserNationalCode,
            Address = _model.UserAddressText,
            PostalCode = _model.PostalCode,
            PaymentStatus = _model.PaymentStatus switch
            {
                PaymentStatus.Success => "پرداخت شده",
                PaymentStatus.Pending => "در انتظار پرداخت",
                _ => "پرداخت نشده"
            },
            PaymentMethod = GetPaymentMethodText(_model.PaymentMethod.GetHashCode()),
            TransactionId = _model.TransactionId?.ToString(),
            TrackingCode = _trackingCode ?? _model.TrackingCode,
            Created = null,
            PaymentDate = _model.PaymentDate?.ToDateTime(),
            Subtotal = subtotal,
            DiscountTotal = discountTotal,
            VatAmount = vat?.VatAmount ?? 0,
            TotalAmount = total,
            Lines = lines
        });

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

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