using BimAI.UI.Shared.Services;
using Microsoft.AspNetCore.Components;
using BimAI.Application.DTOModels;
using BimAI.Application.DTOModels.Common;
using MudBlazor;

namespace BimAI.UI.Shared.Components;

public partial class InvoiceListComponent : ComponentBase
{
    [Inject] private InvoiceService InvoiceService { get; set; } = default!;

    private PagedResult<InvoiceDto> invoices = new();
    private InvoiceFilterRequest filterRequest = new();
    private bool isLoading = false;

    protected override async Task OnInitializedAsync()
    {
        Console.WriteLine("========== InvoiceListComponent OnInitializedAsync ==========");
        await LoadInvoices();
    }

    private async Task LoadInvoices()
    {
        isLoading = true;
        Console.WriteLine($"========== LoadInvoices - Starting load with Page: {filterRequest.Page}, PageSize: {filterRequest.PageSize} ==========");

        try
        {
            invoices = await InvoiceService.GetInvoiceAsync(filterRequest);
            Console.WriteLine($"========== LoadInvoices - Loaded {invoices.Items?.Count ?? 0} invoices, Total: {invoices.TotalCount} ==========");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"========== ERROR Loading invoices failed: {ex.Message} ==========");
            Console.WriteLine($"========== ERROR Stack trace: {ex.StackTrace} ==========");
            if (ex.InnerException != null)
            {
                Console.WriteLine($"========== ERROR Inner exception: {ex.InnerException.Message} ==========");
            }
        }
        finally
        {
            isLoading = false;
        }
    }

    private async Task SearchInvoices()
    {
        filterRequest.Page = 1;
        await LoadInvoices();
    }

    private async Task OnPageChanged(int page)
    {
        filterRequest.Page = page;
        await LoadInvoices();
    }

    private async Task ClearFilters()
    {
        filterRequest = new InvoiceFilterRequest();
        await LoadInvoices();
    }

    private async Task ViewInvoice(Guid invoiceId)
    {
        // TODO
        Console.WriteLine($"Zobacz fakturę: {invoiceId}");
    }

    private async Task EditInvoice(Guid invoiceId)
    {
        // TODO
        Console.WriteLine($"Edytuj fakturę: {invoiceId}");
    }

    private async Task DeleteInvoice(Guid invoiceId)
    {
        // TODO
        Console.WriteLine($"Usuń fakturę: {invoiceId}");
    }
}