@using Indotalent.Features.Setting.SystemUser
@using Indotalent.Features.Setting.SystemUser.Cqrs
@using MudBlazor
@using Indotalent.Shared.Utils
@inject SystemUserService SystemUserService
@inject ISnackbar Snackbar

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
    <div class="d-flex align-center gap-4">
        <MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
        <div>
            <MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Add New User</MudText>
            <MudText Typo="Typo.body2" Style="color: #64748b;">Fill in the account details and security settings for the new user.</MudText>
        </div>
    </div>
</MudPaper>

<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
    <MudForm @ref="_form" Model="_model" Validation="@(_validator.ValidateValue())">
        <MudGrid Spacing="3">
            <MudItem xs="12">
                <MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Primary Information</MudText>
                <MudDivider Class="mt-2 mb-4" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Full Name</MudText>
                <MudTextField @bind-Value="_model.FullName"
                              For="@(() => _model.FullName)"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Email Address (as Username)</MudText>
                <MudTextField @bind-Value="_model.Email"
                              For="@(() => _model.Email)"
                              TextChanged="OnEmailChanged"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Password</MudText>
                <MudTextField @bind-Value="_model.Password"
                              For="@(() => _model.Password)"
                              InputType="InputType.Password"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Phone Number</MudText>
                <MudTextField @bind-Value="_model.PhoneNumber"
                              For="@(() => _model.PhoneNumber)"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            <MudItem xs="12">
                <MudText Typo="Typo.button" Color="Color.Primary" Class="mt-4" Style="font-weight: 800;">SSO Identifiers</MudText>
                <MudDivider Class="mt-2 mb-4" />
            </MudItem>

            <MudItem xs="12" sm="4">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Firebase ID</MudText>
                <MudTextField @bind-Value="_model.SsoIdFirebase" For="@(() => _model.SsoIdFirebase)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Keycloak ID</MudText>
                <MudTextField @bind-Value="_model.SsoIdKeycloak" For="@(() => _model.SsoIdKeycloak)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Azure ID</MudText>
                <MudTextField @bind-Value="_model.SsoIdAzure" For="@(() => _model.SsoIdAzure)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudText Typo="Typo.subtitle2" Class="mb-1">AWS ID</MudText>
                <MudTextField @bind-Value="_model.SsoIdAws" For="@(() => _model.SsoIdAws)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Other SSO ID 1</MudText>
                <MudTextField @bind-Value="_model.SsoIdOther1" For="@(() => _model.SsoIdOther1)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Other SSO ID 2</MudText>
                <MudTextField @bind-Value="_model.SsoIdOther2" For="@(() => _model.SsoIdOther2)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>
            <MudItem xs="12" sm="4">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Other SSO ID 3</MudText>
                <MudTextField @bind-Value="_model.SsoIdOther3" For="@(() => _model.SsoIdOther3)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            <MudItem xs="12">
                <MudText Typo="Typo.button" Color="Color.Primary" Class="mt-4" Style="font-weight: 800;">Account Settings & Status</MudText>
                <MudDivider Class="mt-2 mb-4" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudStack Spacing="4">
                    <div>
                        <MudSwitch @bind-Value="_model.IsActive" Color="Color.Success" Label="Is Active" />
                        <MudText Typo="Typo.caption" Class="ml-10 d-block mt-n2" Style="color: #64748b;">General availability of the account in the system.</MudText>
                    </div>

                    <div>
                        <MudSwitch @bind-Value="_model.EmailConfirmed" Color="Color.Info" Label="Email Confirmed" />
                        <MudText Typo="Typo.caption" Class="ml-10 d-block mt-n2" Style="color: #64748b;">Mark email as verified without requiring user action.</MudText>
                    </div>

                    <div>
                        <MudSwitch @bind-Value="_model.PhoneNumberConfirmed" Color="Color.Info" Label="Phone Confirmed" />
                        <MudText Typo="Typo.caption" Class="ml-10 d-block mt-n2" Style="color: #64748b;">Mark phone number as verified.</MudText>
                    </div>

                    <div>
                        <MudSwitch @bind-Value="_model.TwoFactorEnabled" Color="Color.Warning" Label="Enable 2FA" />
                        <MudText Typo="Typo.caption" Class="ml-10 d-block mt-n2" Style="color: #64748b;">Enforce Two-Factor Authentication for this user.</MudText>
                    </div>
                </MudStack>
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudStack Spacing="4">
                    <div>
                        <MudSwitch @bind-Value="_model.LockoutEnabled" Color="Color.Error" Label="Lockout Enabled" />
                        <MudText Typo="Typo.caption" Class="ml-10 d-block mt-n2" Style="color: #64748b;">Allow account to be locked after failed attempts.</MudText>
                    </div>

                    <div class="mt-2">
                        <MudText Typo="Typo.subtitle2" Class="mb-1">Manual Lockout Until</MudText>
                        <MudDatePicker @bind-Date="_lockoutDate"
                                       Placeholder="Select Date"
                                       Variant="Variant.Outlined"
                                       Margin="Margin.Dense"
                                       Editable="true"
                                       Clearable="true"
                                       MinDate="DateTime.Today" />
                        <MudText Typo="Typo.caption" Style="color: #64748b;">Set this only if you want to pre-lock this new account.</MudText>
                    </div>
                </MudStack>
            </MudItem>
        </MudGrid>

        <div class="d-flex justify-end gap-2 mt-8">
            <MudButton OnClick="() => OnCancel.InvokeAsync()"
                       Variant="Variant.Outlined"
                       Disabled="_processing"
                       Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">
                Cancel
            </MudButton>
            <MudButton Color="Color.Primary"
                       Variant="Variant.Filled"
                       OnClick="Submit"
                       Disabled="_processing"
                       Style="border-radius: 4px; text-transform: none; font-weight: 700;">
                @if (_processing)
                {
                    <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                    <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
                }
                else
                {
                    <MudText>Create User</MudText>
                }
            </MudButton>
        </div>
    </MudForm>
</MudPaper>

@code {
    [Parameter] public EventCallback OnCancel { get; set; }
    [Parameter] public EventCallback OnSuccess { get; set; }

    private MudForm _form = default!;
    private CreateSystemUserRequest _model = new() { IsActive = true, LockoutEnabled = true };
    private CreateSystemUserValidator _validator = new();
    private DateTime? _lockoutDate;
    private bool _processing = false;

    private void OnEmailChanged(string value)
    {
        _model.Email = value;
        _model.UserName = value;
    }

    private async Task Submit()
    {
        await _form.Validate();
        if (!_form.IsValid) return;

        _processing = true;
        try
        {
            if (_lockoutDate.HasValue)
            {
                _model.LockoutEnd = new DateTimeOffset(_lockoutDate.Value, TimeSpan.Zero);
            }
            else
            {
                _model.LockoutEnd = null;
            }

            var response = await SystemUserService.CreateSystemUserAsync(_model);
            await Task.Delay(500);

            if (response != null && response.IsSuccess)
            {
                Snackbar.Add("User created successfully", Severity.Success);
                await OnSuccess.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Error: {ex.Message}", Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }
}