@page "/store"

@using Moonlight.App.Database.Entities.Store
@using Moonlight.App.Models.Enums
@using Moonlight.App.Repositories
@using Moonlight.App.Services
@using Moonlight.App.Services.Store
@using Moonlight.Shared.Components.Store

@inject Repository<Category> CategoryRepository
@inject Repository<Product> ProductRepository
@inject ConfigService ConfigService
@inject IdentityService IdentityService
@inject AlertService AlertService
@inject ToastService ToastService
@inject StoreService StoreService

@{
    var currency = ConfigService.Get().Store.Currency;
}

@if (IdentityService.Permissions[Permission.AdminStore])
{
    <div class="alert alert-info bg-info text-white text-center py-2">
        @if (EditMode)
        {
            <h4 class="pt-2">Edit mode enabled. Disable it by clicking <a href="#" @onclick="ToggleEdit" @onclick:preventDefault>here</a></h4>
        }
        else
        {
            <h4 class="pt-2">To edit the store you can enable the edit mode <a href="#" @onclick="ToggleEdit" @onclick:preventDefault>here</a></h4>
        }
    </div>
}

<div class="row">
    <div class="col-md-3 col-12 mb-5">
        <div class="card">
            <div class="card-header">
                <h6 class="card-title">Categories</h6>
                @if (EditMode)
                {
                    <div class="card-toolbar">
                        <button @onclick="() => StoreModals.AddCategoryShow" class="btn btn-icon btn-success">
                            <i class="bx bx-sm bx-plus"></i>
                        </button>
                    </div>
                }
            </div>
            <div class="card-body">
                <LazyLoader @ref="CategoriesLazyLoader" Load="LoadCategories">
                    @foreach (var category in Categories)
                    {
                        <div class="d-flex flex-column">
                            <li class="d-flex align-items-center py-2">
                                <span class="bullet me-5"></span>
                                <a class="invisible-a fs-5 @(SelectedCategory == category ? "fw-bold text-primary" : "")" href="/store?category=@(category.Slug)">@(category.Name)</a>
                                @if (EditMode)
                                {
                                    <a @onclick="() => StoreModals.EditCategoryShow(category)" @onclick:preventDefault href="#" class="ms-3 text-warning">Edit</a>
                                    <a @onclick="() => DeleteCategory(category)" @onclick:preventDefault href="#" class="ms-1 text-danger">Delete</a>
                                }
                            </li>
                        </div>
                    }
                </LazyLoader>
            </div>
        </div>
    </div>
    <div class="col-md-9 col-12">
        <LazyLoader @ref="ProductsLazyLoader" Load="LoadProducts">
            @if (Products.Any())
            {
                <div class="row">
                    @foreach (var product in Products)
                    {
                        <div class="col-md-4 col-12 mb-5">
                            <div class="card">
                                @if (EditMode)
                                {
                                    <div class="card-header">
                                        <a @onclick="() => StoreModals.EditProductShow(product)" @onclick:preventDefault href="#" class="card-title text-primary">Edit</a>
                                        <div class="card-toolbar">
                                            <a @onclick="() => DeleteProduct(product)" @onclick:preventDefault href="#" class="text-danger">Delete</a>
                                        </div>
                                    </div>
                                }
                                <div class="card-body text-center">
                                    <h1 class="text-dark mb-5 fw-bolder">@(product.Name)</h1>
                                    <p class="fw-semibold fs-6 text-gray-800 flex-grow-1">
                                        @(Formatter.FormatLineBreaks(product.Description))
                                    </p>

                                    <div class="text-center mb-8">
                                        @if (product.Price == 0)
                                        {
                                            <span class="fs-1 fw-bold text-primary">
                                                Free
                                            </span>
                                        }
                                        else
                                        {
                                            <span class="mb-2 text-primary">@(currency)</span>
                                            <span class="fs-1 fw-bold text-primary">
                                                @(product.Price)
                                            </span>
                                            <span class="fs-7 fw-semibold opacity-50">
                                                /
                                                <span>@(product.Duration) days</span>
                                            </span>
                                        }
                                    </div>

                                    @if (product.Stock == 0)
                                    {
                                        <button class="btn btn-primary disabled">Out of stock</button>
                                    }
                                    else
                                    {
                                        <a href="/store/order/@(product.Slug)" class="btn btn-primary">Order now</a>
                                    }
                                </div>
                            </div>
                        </div>
                    }

                    @if (EditMode)
                    {
                        <div class="col-md-4 col-12 mb-5">
                            <div class="card">
                                <div class="card-body text-center">
                                    <button @onclick="() => StoreModals.AddProductShow" class="btn btn-success">Create new product</button>
                                </div>
                            </div>
                        </div>
                    }
                </div>
            }
            else
            {
                if (Categories.Any())
                {
                    if (EditMode)
                    {
                        <div class="card">
                            <div class="card-body text-center py-10">
                                <button @onclick="() => StoreModals.AddProductShow" class="btn btn-success">Create new product</button>
                            </div>
                        </div>
                    }
                    else
                    {
                        <div class="card card-body text-center">
                            <div class="py-10">
                                <h1 class="card-title">Welcome to our store</h1>
                                <span class="card-subtitle fs-2">Select a category to start browsing</span>
                            </div>

                            <div class="py-10 text-center p-10">
                                <img src="/svg/shopping.svg" style="height: 10vi" alt="Banner">
                            </div>
                        </div>
                    }
                }
                else
                {
                    <div class="card card-body text-center">
                        <h1 class="card-title py-10">No products found</h1>
                    </div>
                }
            }
        </LazyLoader>
    </div>
</div>

<StoreModals @ref="StoreModals" OnUpdate="OnParametersSetAsync" />

@code
{
    // Category
    private Category[] Categories;
    private LazyLoader? CategoriesLazyLoader;

    [Parameter]
    [SupplyParameterFromQuery]
    public string Category { get; set; }

    private Category? SelectedCategory;

    // Products
    private Product[] Products;
    private LazyLoader? ProductsLazyLoader;

    // Edit stuff
    private bool EditMode = false;
    private StoreModals StoreModals;

    protected override async Task OnParametersSetAsync()
    {
        if (CategoriesLazyLoader != null)
            await CategoriesLazyLoader.Reload();

        if (ProductsLazyLoader != null)
            await ProductsLazyLoader.Reload();
    }

    private async Task ToggleEdit()
    {
        EditMode = !EditMode;
        await InvokeAsync(StateHasChanged);
    }

    private Task LoadCategories(LazyLoader _)
    {
        Categories = CategoryRepository.Get().ToArray();

        SelectedCategory = Categories.FirstOrDefault(x => x.Slug == Category);

        return Task.CompletedTask;
    }

    private Task LoadProducts(LazyLoader _)
    {
        if (SelectedCategory == null)
        {
            Products = ProductRepository
                .Get()
                .Where(x => x.Category == null)
                .ToArray();
        }
        else
        {
            Products = ProductRepository
                .Get()
                .Where(x => x.Category!.Id == SelectedCategory.Id)
                .ToArray();
        }

        return Task.CompletedTask;
    }

    private async Task DeleteCategory(Category category)
    {
        if (!await AlertService.YesNo($"Do you really want to delete '{category.Name}'", "Continue", "Cancel"))
            return;

        await StoreService.Admin.DeleteCategory(category);
        
        await ToastService.Success("Successfully deleted category");
        await OnParametersSetAsync();
    }
    
    private async Task DeleteProduct(Product product)
    {
        if (!await AlertService.YesNo($"Do you really want to delete '{product.Name}'", "Continue", "Cancel"))
            return;

        await StoreService.Admin.DeleteProduct(product);
        
        await ToastService.Success("Successfully deleted product");
        await OnParametersSetAsync();
    }
}