@page "/tenant-management"
@using MudBlazor
@inject ISnackbar Snackbar

<PageTitle>Mandantenverwaltung | OnProf</PageTitle>

<MudContainer MaxWidth="MaxWidth.ExtraLarge" Class="mt-8">
    <div class="d-flex justify-space-between align-center mb-6">
        <div>
            <MudText Typo="Typo.h4" Class="fw-bold">Mandantenverwaltung</MudText>
            <MudText Typo="Typo.body1" Color="Color.Secondary" Class="mt-1">Übersicht und Settings der Firmen und Mandanten im System.</MudText>
        </div>
        <MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Business" OnClick="OpenAddModal">Neuen Mandant</MudButton>
    </div>

    <MudPaper Elevation="2" Class="pa-4">
        <MudDataGrid T="Tenant" Items="@_tenants" Hover="true" Bordered="false" Striped="true" QuickFilter="@_quickFilter">
            <ToolBarContent>
                <MudTextField @bind-Value="_searchString" Placeholder="Nach Mandant suchen..." Adornment="Adornment.Start" Immediate="true"
                              AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0" 
                              Variant="Variant.Outlined" Margin="Margin.Dense" Style="max-width: 300px;"></MudTextField>
                <MudSpacer />
            </ToolBarContent>
            <Columns>
                <TemplateColumn T="Tenant" Title="Mandant" SortBy="@(x => x.Name)">
                    <CellTemplate>
                        <div class="d-flex align-center">
                            <MudAvatar Size="Size.Small" Color="Color.Primary" Class="mr-3" Variant="Variant.Outlined">
                                <MudIcon Icon="@Icons.Material.Filled.Business" Size="Size.Small" />
                            </MudAvatar>
                            <MudText Typo="Typo.body1"><b>@context.Item.Name</b></MudText>
                        </div>
                    </CellTemplate>
                </TemplateColumn>
                <PropertyColumn Property="x => x.ContactPerson" Title="Hauptansprechpartner" />
                <TemplateColumn T="Tenant" Title="Status">
                    <CellTemplate>
                        @if (context.Item.IsActive)
                        {
                            <MudChip T="string" Color="Color.Success" Size="Size.Small" Variant="Variant.Filled">Aktiv</MudChip>
                        }
                        else
                        {
                            <MudChip T="string" Color="Color.Error" Size="Size.Small" Variant="Variant.Filled">Inaktiv</MudChip>
                        }
                    </CellTemplate>
                </TemplateColumn>
                <PropertyColumn Property="x => x.EmployeeCount" Title="Mitarbeiter" />
                <TemplateColumn T="Tenant" CellClass="d-flex justify-end pr-4">
                    <CellTemplate>
                        <MudTooltip Text="Bearbeiten" Delay="400">
                            <MudIconButton Size="@Size.Small" Icon="@Icons.Material.Filled.Edit" Color="Color.Primary" OnClick="() => EditTenant(context.Item)" />
                        </MudTooltip>
                    </CellTemplate>
                </TemplateColumn>
            </Columns>
            <PagerContent>
                <MudDataGridPager T="Tenant" RowsPerPageString="Einträge pro Seite:" />
            </PagerContent>
        </MudDataGrid>
    </MudPaper>
</MudContainer>

<MudDialog @bind-Visible="_isModalOpen" Options="new DialogOptions { MaxWidth = MaxWidth.Small, FullWidth = true }">
    <TitleContent>
        <MudText Typo="Typo.h6">@(_isEditing ? "Mandant bearbeiten" : "Neuen Mandant anlegen")</MudText>
    </TitleContent>
    <DialogContent>
        <MudTextField @bind-Value="_currentTenant.Name" Label="Name des Mandanten" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3" Required="true" />
        <MudTextField @bind-Value="_currentTenant.ContactPerson" Label="Hauptansprechpartner" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3" Required="true" />
        
        <MudSwitch @bind-Value="_currentTenant.IsActive" Label="Ist Aktiv" Color="Color.Success" Class="mt-2" />
        
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="CloseModal">Abbrechen</MudButton>
        <MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="SaveTenant">Speichern</MudButton>
    </DialogActions>
</MudDialog>

@code {
    private string _searchString = "";
    private bool _isModalOpen = false;
    private bool _isEditing = false;
    private Tenant _currentTenant = new();

    public class Tenant
    {
        public Guid Id { get; set; } = Guid.NewGuid();
        public string Name { get; set; } = string.Empty;
        public string ContactPerson { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
        public int EmployeeCount { get; set; }
    }

    private List<Tenant> _tenants = new()
    {
        new Tenant { Name = "OnProf GmbH", ContactPerson = "Marc Mustermann", IsActive = true, EmployeeCount = 15 },
        new Tenant { Name = "SubCorp AG", ContactPerson = "Anna Schmidt", IsActive = true, EmployeeCount = 42 },
        new Tenant { Name = "Freelancer Network", ContactPerson = "Peter Parker", IsActive = false, EmployeeCount = 5 },
        new Tenant { Name = "Test-Mandant", ContactPerson = "Maria Mayer", IsActive = true, EmployeeCount = 2 }
    };

    private Func<Tenant, bool> _quickFilter => x =>
    {
        if (string.IsNullOrWhiteSpace(_searchString)) return true;
        if (x.Name.Contains(_searchString, StringComparison.OrdinalIgnoreCase)) return true;
        if (x.ContactPerson.Contains(_searchString, StringComparison.OrdinalIgnoreCase)) return true;
        return false;
    };

    private void OpenAddModal()
    {
        _isEditing = false;
        _currentTenant = new Tenant();
        _isModalOpen = true;
    }

    private void EditTenant(Tenant tenant)
    {
        _isEditing = true;
        _currentTenant = new Tenant
        {
            Id = tenant.Id,
            Name = tenant.Name,
            ContactPerson = tenant.ContactPerson,
            IsActive = tenant.IsActive,
            EmployeeCount = tenant.EmployeeCount
        };
        _isModalOpen = true;
    }

    private void SaveTenant()
    {
        if (string.IsNullOrWhiteSpace(_currentTenant.Name) || string.IsNullOrWhiteSpace(_currentTenant.ContactPerson))
        {
            Snackbar.Add("Name und Ansprechpartner sind Pflichtfelder.", Severity.Error);
            return;
        }

        if (_isEditing)
        {
            var index = _tenants.FindIndex(t => t.Id == _currentTenant.Id);
            if (index != -1)
            {
                _tenants[index] = _currentTenant;
                Snackbar.Add("Änderungen gespeichert.", Severity.Success);
            }
        }
        else
        {
            // Set dummy count for UI purpose
            _currentTenant.EmployeeCount = 0; 
            _tenants.Add(_currentTenant);
            Snackbar.Add("Neuer Mandant angelegt.", Severity.Success);
        }

        CloseModal();
    }

    private void CloseModal()
    {
        _isModalOpen = false;
    }
}