@using Moonlight.App.Database.Entities.Store
@using Moonlight.App.Services
@using Moonlight.App.Services.ServiceManage
@using Moonlight.App.Services.Store
@using Moonlight.Shared.Components.Modals

@inject ConfigService ConfigService
@inject ToastService ToastService
@inject ServiceService ServiceService
@inject StoreService StoreService
@inject IdentityService IdentityService

@if (ShowDeletionScreen)
{
    <div class="card">
        <div class="card-header">
            <h3 class="card-title align-items-start flex-column">
                <span class="card-label fw-bold text-dark fs-3">Do you really want to delete @(Service.Nickname ?? $"Service {Service.Id}")</span>
            </h3>
        </div>
        <div class="card-body">
            <p class="text-gray-400 fs-5 fw-semibold">
                This action cannot be undone. Your service data will be deleted and cannot be restored
            </p>
        </div>
        <div class="card-footer p-3">
            <div class="btn-group w-100">
                <WButton OnClick="Delete" Text="Delete" CssClasses="btn btn-danger w-50 me-3"/>
                <button @onclick="() => SetShowDeletion(false)" class="btn btn-secondary w-50">Cancel</button>
            </div>
        </div>
    </div>
}
else if (ShowRenewScreen)
{
    <div class="card">
        <div class="card-header">
            <h3 class="card-title align-items-start flex-column">
                <span class="card-label fw-bold text-dark fs-3">Do you want to renew @(Service.Nickname ?? $"Service {Service.Id}")</span>
            </h3>
        </div>
        <div class="card-body fs-5">
            <div class="row mb-5">
                <div class="col-md-4 col-12">
                    <a @onclick="() => SetDurationMultiplier(1)" @onclick:preventDefault href="#" class="card card-body bg-hover-secondary text-center @(DurationMultiplier == 1 ? "border border-info" : "")">
                        <h6 class="fw-bold mb-0 align-middle">@(Service.Product.Duration * 1) days</h6>
                    </a>
                </div>
                <div class="col-md-4 col-12">
                    <a @onclick="() => SetDurationMultiplier(2)" @onclick:preventDefault href="#" class="card card-body bg-hover-secondary text-center @(DurationMultiplier == 2 ? "border border-info" : "")">
                        <h6 class="fw-bold mb-0 align-middle">@(Service.Product.Duration * 2) days</h6>
                    </a>
                </div>
                <div class="col-md-4 col-12">
                    <a @onclick="() => SetDurationMultiplier(3)" @onclick:preventDefault href="#" class="card card-body bg-hover-secondary text-center @(DurationMultiplier == 3 ? "border border-info" : "")">
                        <h6 class="fw-bold mb-0 align-middle">@(Service.Product.Duration * 3) days</h6>
                    </a>
                </div>
            </div>

            @{
                var actualPrice = Service.Product.Price * DurationMultiplier;
                var currency = ConfigService.Get().Store.Currency;
            }

            <div class="d-flex flex-stack">
                <div class="text-gray-700 fw-semibold me-2">Today</div>
                <div class="d-flex align-items-senter">
                    <span class="fw-bold">@(currency) @(actualPrice)</span>
                </div>
            </div>
            <div class="d-flex flex-stack">
                <div class="text-gray-700 fw-semibold me-2">Renew</div>
                <div class="d-flex align-items-senter">
                    <span class="fw-bold">@(currency) @(Service.Product.Price)</span>
                </div>
            </div>
            <div class="d-flex flex-stack">
                <div class="text-gray-700 fw-semibold me-2">Duration</div>
                <div class="d-flex align-items-senter">
                    <span class="fw-bold">@(Service.Product.Duration * DurationMultiplier) days</span>
                </div>
            </div>
            <div class="separator my-4"></div>
            <div class="d-flex flex-stack">
                <div class="text-gray-700 fw-semibold me-2">Total</div>
                <div class="d-flex align-items-senter">
                    <span class="fw-bold">@(currency) @(actualPrice)</span>
                </div>
            </div>
            <div class="mt-7">
                @if (!CanBeRenewed && !string.IsNullOrEmpty(ErrorMessage))
                {
                    <div class="alert alert-warning bg-warning text-white text-center">
                        @ErrorMessage
                    </div>
                }
            </div>
            <div class="mt-5">
                @if (IsValidating)
                {
                    <button class="btn btn-primary w-100 disabled" disabled="">
                        <span class="spinner-border spinner-border-sm align-middle"></span>
                    </button>
                }
                else
                {
                    if (CanBeRenewed)
                    {
                        <WButton OnClick="Renew" Text="@($"Renew for {currency} {actualPrice}")" CssClasses="btn btn-primary w-100"/>
                    }
                    else
                    {
                        <button class="btn btn-primary w-100 disabled" disabled="">Order for @(currency) @(actualPrice)</button>
                    }
                }
            </div>
        </div>
        <div class="card-footer p-3">
            <div class="btn-group w-100">
                <button @onclick="() => SetShowRenew(false)" class="btn btn-secondary">Cancel</button>
            </div>
        </div>
    </div>
}
else
{
    <div class="card">
        <div class="card-header">
            <h3 class="card-title align-items-start flex-column">
                <span class="card-label fw-bold text-dark fs-3">@(Service.Nickname ?? $"Service {Service.Id}")</span>
                <span class="text-gray-400 mt-1 fw-semibold fs-6">@(Service.Product.Name)</span>
            </h3>
        </div>
        <div class="card-body fs-6">
            <div class="d-flex flex-stack">
                <div class="text-gray-700 fw-semibold me-2">Renew price</div>
                <div class="d-flex align-items-senter">
                    <span class="fw-bold">@(ConfigService.Get().Store.Currency) @(Service.Product.Price)</span>
                </div>
            </div>
            <div class="d-flex flex-stack">
                <div class="text-gray-700 fw-semibold me-2">Renew at</div>
                <div class="d-flex align-items-senter">
                    <span class="fw-bold">@(Formatter.FormatDate(Service.RenewAt))</span>
                </div>
            </div>
            <div class="d-flex flex-stack">
                <div class="text-gray-700 fw-semibold me-2">Created at</div>
                <div class="d-flex align-items-senter">
                    <span class="fw-bold">@(Formatter.FormatDate(Service.CreatedAt))</span>
                </div>
            </div>
        </div>
        <div class="card-footer p-3">
            <div class="btn-group w-100 mb-3">
                <a href="/service/@(Service.Id)" class="btn btn-primary w-50 me-3">Manage</a>
                <button @onclick="() => ShareModal.Show()" class="btn btn-secondary w-50">Manage shares</button>
            </div>
            <div class="btn-group w-100">
                <button @onclick="() => SetShowRenew(true)" class="btn btn-warning w-50 me-3">Renew</button>
                <button @onclick="() => SetShowDeletion(true)" class="btn btn-danger w-50">Delete</button>
            </div>
        </div>
    </div>

    <ManageServiceShareModal @ref="ShareModal" Service="Service"/>
}



@code
{
    [Parameter]
    public Service Service { get; set; }

    [Parameter]
    public Func<Task> OnChange { get; set; }

    private bool ShowDeletionScreen = false;
    private bool ShowRenewScreen = false;
    private ManageServiceShareModal ShareModal;

    private int DurationMultiplier = 1;
    private bool CanBeRenewed = false;
    private bool IsValidating = false;
    private string ErrorMessage = "";

    private Task Revalidate()
    {
        IsValidating = true;
        InvokeAsync(StateHasChanged);

        Task.Run(async () =>
        {
            try
            {
                await StoreService.Order.ValidateRenew(IdentityService.CurrentUser, Service, DurationMultiplier);
                CanBeRenewed = true;
            }
            catch (DisplayException e)
            {
                CanBeRenewed = false;
                ErrorMessage = e.Message;
            }

            IsValidating = false;
            await InvokeAsync(StateHasChanged);
        });

        return Task.CompletedTask;
    }

    private async Task Renew()
    {
        await StoreService.Order.Renew(IdentityService.CurrentUser, Service, DurationMultiplier);

        await ToastService.Success("Successfully renewed service");
        await OnChange.Invoke();
    }

    private async Task SetDurationMultiplier(int i)
    {
        DurationMultiplier = i;
        await Revalidate();
    }

    private async Task SetShowDeletion(bool b)
    {
        ShowDeletionScreen = b;
        await InvokeAsync(StateHasChanged);
    }

    private async Task SetShowRenew(bool b)
    {
        ShowRenewScreen = b;

        if (b) // Revalidate when the renew screen is shown
            await Revalidate();

        await InvokeAsync(StateHasChanged);
    }

    public async Task Delete()
    {
        await ServiceService.Admin.Delete(Service);

        await ToastService.Success("Successfully deleted service");
        await OnChange.Invoke();
    }
}