@page "/admin/customers"
@layout AdminLayout
@using FilterCair.Shared.Models
@inject FilterCair.Client.Services.API.CustomerService CustomerService
@inject IJSRuntime JS

<PageTitle>Kunden verwalten</PageTitle>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <h4 class="text-primary mb-0">
            <i class="bi bi-buildings me-2"></i> Kundenverwaltung
        </h4>
        <button class="btn btn-success rounded-pill" @onclick="ShowCreateModal">
            <i class="bi bi-plus-lg me-1"></i> Neuer Kunde
        </button>
    </div>

    @if (isLoading)
    {
        <div class="text-center py-5 text-muted">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-3">Lade Kunden...</p>
        </div>
    }
    else if (customers.Count == 0)
    {
        <div class="alert alert-info text-center">
            Keine Kunden vorhanden. Lege den ersten Kunden an!
        </div>
    }
    else
    {
        <div class="table-responsive">
            <table class="table table-striped align-middle shadow-sm">
                <thead class="table-primary">
                    <tr>
                        <th>Name</th>
                        <th>Standort</th>
                        <th>Ansprechpartner</th>
                        <th>Telefon</th>
                        <th>Email</th>
                        <th style="width:160px;"></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var c in customers)
                    {
                        <tr>
                            <td>@c.Name</td>
                            <td>@c.Standort</td>
                            <td>@c.Ansprechpartner</td>
                            <td>@c.Telefon</td>
                            <td>@c.Email</td>
                            <td class="text-end">
                                <button class="btn btn-outline-primary btn-sm rounded-pill me-1"
                                        @onclick="() => ShowEditModal(c)">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-outline-danger btn-sm rounded-pill"
                                        @onclick="() => DeleteCustomer(c)">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    }

    <!-- Modal -->
    @if (showModal)
    {
        <div class="modal fade show d-block" tabindex="-1" style="background-color:rgba(0,0,0,0.5);">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow-lg rounded-4">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">
                            <i class="bi @(isEditMode ? "bi-pencil" : "bi-person-plus") me-2"></i>
                            @(isEditMode ? "Kunde bearbeiten" : "Neuer Kunde")
                        </h5>
                        <button type="button" class="btn-close btn-close-white" @onclick="CloseModal"></button>
                    </div>
                    <div class="modal-body">
                        <EditForm Model="@newCustomer" OnValidSubmit="SaveCustomer">
                            <DataAnnotationsValidator />
                            <ValidationSummary />

                            <div class="mb-3">
                                <label class="form-label">Name</label>
                                <InputText class="form-control" @bind-Value="newCustomer.Name" required />
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Standort</label>
                                <InputText class="form-control" @bind-Value="newCustomer.Standort" required />
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Ansprechpartner</label>
                                <InputText class="form-control" @bind-Value="newCustomer.Ansprechpartner" />
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Telefon</label>
                                <InputText class="form-control" @bind-Value="newCustomer.Telefon" />
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Email</label>
                                <InputText class="form-control" @bind-Value="newCustomer.Email" />
                            </div>

                            <div class="text-end">
                                <button type="button" class="btn btn-outline-secondary me-2 rounded-pill" @onclick="CloseModal">Abbrechen</button>
                                <button type="submit" class="btn btn-success rounded-pill">
                                    @(isEditMode ? "Aktualisieren" : "Speichern")
                                </button>
                            </div>
                        </EditForm>
                    </div>
                </div>
            </div>
        </div>
    }
</div>

@code {
    private List<CustomerModel> customers = new();
    private CustomerModel newCustomer = new();
    private bool showModal = false;
    private bool isEditMode = false;
    private bool isLoading = true;

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

    private async Task LoadCustomers()
    {
        isLoading = true;
        customers = await CustomerService.GetCustomersAsync();
        isLoading = false;
    }

    private void ShowCreateModal()
    {
        newCustomer = new CustomerModel();
        isEditMode = false;
        showModal = true;
    }

    private void ShowEditModal(CustomerModel c)
    {
        newCustomer = new CustomerModel
        {
            Id = c.Id,
            Name = c.Name,
            Standort = c.Standort,
            Ansprechpartner = c.Ansprechpartner,
            Telefon = c.Telefon,
            Email = c.Email
        };
        isEditMode = true;
        showModal = true;
    }

    private void CloseModal()
    {
        showModal = false;
    }

    private async Task SaveCustomer()
    {
        bool success;

        if (isEditMode)
            success = await CustomerService.UpdateCustomerAsync(newCustomer);
        else
            success = await CustomerService.AddCustomerAsync(newCustomer);

        if (success)
        {
            await LoadCustomers();
            CloseModal();
            await JS.InvokeVoidAsync("showToast", "✅ Erfolgreich gespeichert!");
        }
        else
        {
            await JS.InvokeVoidAsync("showToast", "❌ Fehler beim Speichern.", "error");
        }
    }

    private async Task DeleteCustomer(CustomerModel customer)
    {
        bool confirmed = await JS.InvokeAsync<bool>("confirm", $"Soll der Kunde '{customer.Name}' wirklich gelöscht werden?");
        if (!confirmed) return;

        var success = await CustomerService.DeleteCustomerAsync(customer.Id);
        if (success)
        {
            customers.Remove(customer);
            await JS.InvokeVoidAsync("showToast", "🗑️ Kunde gelöscht");
        }
        else
        {
            await JS.InvokeVoidAsync("showToast", "❌ Fehler beim Löschen.", "error");
        }
    }
}
