@page "/products"
@inject HttpClient Http

@* 
    EN: Products page demonstrating shared validation between Client and Server.
    VI: Trang sản phẩm demo validation được chia sẻ giữa Client và Server.
*@

<PageTitle>Products / Sản phẩm</PageTitle>

<div class="container">
    <h1 class="page-title">Products Management / Quản lý sản phẩm</h1>
    
    @* ═══════════════════════════════════════════════════════════════════════════════
       EN: Create Product Form with shared validation
       VI: Form tạo sản phẩm với validation được chia sẻ
       ═══════════════════════════════════════════════════════════════════════════════ *@
    <section class="glass-card">
        <h2>Create Product / Tạo sản phẩm</h2>
        
        <EditForm Model="@newProduct" OnValidSubmit="HandleSubmit" OnInvalidSubmit="HandleInvalid" FormName="CreateProduct">
            @* EN: DataAnnotationsValidator uses the same validation rules as the Server
               VI: DataAnnotationsValidator sử dụng cùng validation rules với Server *@
            <DataAnnotationsValidator />
            
            @* EN: Display all validation errors
               VI: Hiển thị tất cả lỗi validation *@
            <ValidationSummary class="validation-summary" />
            
            <div class="form-group">
                <label for="name">Product Name / Tên sản phẩm *</label>
                <InputText id="name" @bind-Value="newProduct.Name" class="form-input" placeholder="Enter product name..." />
                <ValidationMessage For="() => newProduct.Name" class="validation-message" />
            </div>
            
            <div class="form-group">
                <label for="description">Description / Mô tả</label>
                <InputTextArea id="description" @bind-Value="newProduct.Description" class="form-input" rows="3" placeholder="Enter description..." />
                <ValidationMessage For="() => newProduct.Description" class="validation-message" />
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="price">Price / Giá *</label>
                    <InputNumber id="price" @bind-Value="newProduct.Price" class="form-input" placeholder="0.00" />
                    <ValidationMessage For="() => newProduct.Price" class="validation-message" />
                </div>
                
                <div class="form-group">
                    <label for="quantity">Quantity / Số lượng</label>
                    <InputNumber id="quantity" @bind-Value="newProduct.Quantity" class="form-input" placeholder="0" />
                    <ValidationMessage For="() => newProduct.Quantity" class="validation-message" />
                </div>
            </div>
            
            <div class="form-group">
                <label for="category">Category ID / ID Danh mục *</label>
                <InputText id="category" @bind-Value="categoryIdString" class="form-input" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
                <ValidationMessage For="() => newProduct.CategoryId" class="validation-message" />
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary" disabled="@isSubmitting">
                    @if (isSubmitting)
                    {
                        <span class="spinner"></span>
                        <span>Submitting...</span>
                    }
                    else
                    {
                        <span>Create Product / Tạo sản phẩm</span>
                    }
                </button>
                <button type="button" class="btn btn-secondary" @onclick="ResetForm">Reset</button>
            </div>
        </EditForm>
        
        @if (!string.IsNullOrEmpty(submitMessage))
        {
            <div class="alert @(submitSuccess ? "alert-success" : "alert-error")">
                @submitMessage
            </div>
        }
    </section>

    @* ═══════════════════════════════════════════════════════════════════════════════
       EN: Product List
       VI: Danh sách sản phẩm
       ═══════════════════════════════════════════════════════════════════════════════ *@
    <section class="glass-card">
        <h2>Product List / Danh sách sản phẩm</h2>
        
        @if (products == null)
        {
            <p class="loading">Loading products... / Đang tải sản phẩm...</p>
        }
        else if (!products.Any())
        {
            <p class="empty-state">No products found. / Không tìm thấy sản phẩm.</p>
        }
        else
        {
            <div class="product-grid">
                @foreach (var product in products)
                {
                    <div class="product-card">
                        <h3>@product.Name</h3>
                        <p class="description">@(product.Description ?? "No description")</p>
                        <div class="product-details">
                            <span class="price">@product.Price.ToString("C")</span>
                            <span class="quantity">Stock: @product.Quantity</span>
                        </div>
                    </div>
                }
            </div>
        }
    </section>
</div>

@code {
    private CreateProductDto newProduct = new();
    private List<ProductDto>? products;
    private bool isSubmitting = false;
    private string submitMessage = "";
    private bool submitSuccess = false;
    private string categoryIdString = "";

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

    private async Task LoadProducts()
    {
        try
        {
            var response = await Http.GetFromJsonAsync<ApiResponse<List<ProductDto>>>("api/Products");
            if (response?.Success == true)
            {
                products = response.Data ?? new List<ProductDto>();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error loading products: {ex.Message}");
            products = new List<ProductDto>();
        }
    }

    private async Task HandleSubmit()
    {
        isSubmitting = true;
        submitMessage = "";

        // Parse category ID
        if (Guid.TryParse(categoryIdString, out var categoryId))
        {
            newProduct.CategoryId = categoryId;
        }

        try
        {
            var response = await Http.PostAsJsonAsync("api/Products", newProduct);
            
            if (response.IsSuccessStatusCode)
            {
                submitSuccess = true;
                submitMessage = "Product created successfully! / Tạo sản phẩm thành công!";
                ResetForm();
                await LoadProducts();
            }
            else
            {
                submitSuccess = false;
                var content = await response.Content.ReadAsStringAsync();
                submitMessage = $"Error: {response.StatusCode} - {content}";
            }
        }
        catch (Exception ex)
        {
            submitSuccess = false;
            submitMessage = $"Error: {ex.Message}";
        }
        finally
        {
            isSubmitting = false;
        }
    }

    private void HandleInvalid()
    {
        submitMessage = "Please fix the validation errors. / Vui lòng sửa các lỗi validation.";
        submitSuccess = false;
    }

    private void ResetForm()
    {
        newProduct = new CreateProductDto();
        categoryIdString = "";
    }
}
