using CMSMicroservice.Protobuf.Protos.UserOrder;
using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Messages = CMSMicroservice.Protobuf.Protos;

namespace FrontOffice.Main.Pages.Store;

public partial class OrderTracking : ComponentBase
{
    [Inject] private OrderService OrderService { get; set; } = default!;
    [Inject] private IJSRuntime JS { get; set; } = default!;
    
    [Parameter] public long id { get; set; }
    
    private GetUserOrderResponse? _order;
    private bool _loading = true;
    private List<TrackingStep> _trackingSteps = new();

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

    private async Task LoadOrderAsync()
    {
        _loading = true;
        StateHasChanged();

        try
        {
            var response = await OrderService.GetOrderAsync(id);
            if (response is not null)
            {
                _order = response;
                BuildTrackingSteps();
            }
        }
        finally
        {
            _loading = false;
            StateHasChanged();
        }
    }

    private void BuildTrackingSteps()
    {
        if (_order is null) return;

        var isPaid = _order.PaymentStatus == Messages.PaymentStatus.Success;
        // Domain/public_messages: None=0, Pending=1, InTransit=2, Delivered=3, Returned=4, Cancelled=5, ReadyForOfficePickup=6
        var delivery = (int)_order.DeliveryStatus;
        var isCancelled = delivery == 5;
        var isReturned = delivery == 4;
        var isOfficePickup = delivery == 6;
        var isInTransit = delivery == 2;
        var isDelivered = delivery == 3;
        var isPendingDelivery = delivery is 0 or 1;

        _trackingSteps =
        [
            new()
            {
                Title = "ثبت سفارش",
                Description = "سفارش شما با موفقیت ثبت شد",
                IsCompleted = true,
                Date = FormatDate(_order.PaymentDate)
            },
            new()
            {
                Title = "پرداخت",
                Description = isPaid ? "پرداخت شما تایید شد" : "منتظر تایید پرداخت هستیم",
                IsCompleted = isPaid,
                IsCurrent = !isPaid && !isCancelled,
                Date = isPaid ? FormatDate(_order.PaymentDate) : ""
            }
        ];

        if (isCancelled)
        {
            _trackingSteps.Add(new()
            {
                Title = "لغو شده",
                Description = "ارسال این سفارش لغو شده است",
                IsCompleted = true,
                IsCurrent = true,
                Date = ""
            });
            return;
        }

        if (isReturned)
        {
            _trackingSteps.Add(new()
            {
                Title = "مرجوع شده",
                Description = "سفارش مرجوع شده است",
                IsCompleted = true,
                IsCurrent = true,
                Date = ""
            });
            return;
        }

        if (isOfficePickup)
        {
            _trackingSteps.Add(new()
            {
                Title = "آماده تحویل در دفتر",
                Description = "سفارش برای تحویل حضوری در دفتر آماده است",
                IsCompleted = true,
                IsCurrent = true,
                Date = ""
            });
            return;
        }

        _trackingSteps.Add(new()
        {
            Title = "در حال آماده‌سازی",
            Description = "سفارش شما در حال آماده‌سازی است",
            IsCompleted = isInTransit || isDelivered,
            IsCurrent = isPaid && isPendingDelivery,
            Date = ""
        });
        _trackingSteps.Add(new()
        {
            Title = "ارسال شده",
            Description = "سفارش شما به پست تحویل داده شد",
            IsCompleted = isDelivered,
            IsCurrent = isInTransit,
            Date = ""
        });
        _trackingSteps.Add(new()
        {
            Title = "تحویل داده شده",
            Description = "سفارش به دست شما رسید",
            IsCompleted = isDelivered,
            IsCurrent = false,
            Date = ""
        });
    }

    private static string FormatDate(Google.Protobuf.WellKnownTypes.Timestamp? timestamp)
    {
        if (timestamp is null) return "";
        var date = timestamp.ToDateTime();
        var persianCalendar = new System.Globalization.PersianCalendar();
        return $"{persianCalendar.GetYear(date)}/{persianCalendar.GetMonth(date):00}/{persianCalendar.GetDayOfMonth(date):00}";
    }

    private static string GetPaymentMethodText(Messages.PaymentMethod method) => method switch
    {
        Messages.PaymentMethod.Ipg => "پرداخت آنلاین",
        Messages.PaymentMethod.Wallet => "کیف پول",
        _ => "نامشخص"
    };

    private class TrackingStep
    {
        public string Title { get; set; } = "";
        public string Description { get; set; } = "";
        public bool IsCompleted { get; set; }
        public bool IsCurrent { get; set; }
        public string Date { get; set; } = "";
    }

    private async Task GoBack() => await JS.InvokeVoidAsync("history.back");
}
