@using Indotalent.Features.Utilities.BookingManager
@using Indotalent.Features.Utilities.BookingManager.Cqrs
@using Indotalent.Shared.Utils
@using MudBlazor
@inject BookingManagerService BookingManagerService
@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 Booking</MudText>
            <MudText Typo="Typo.body2" Style="color: #64748b;">Schedule a new resource booking.</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">
        <MudGrid Spacing="3">
            <MudItem xs="12">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Subject</MudText>
                <MudTextField @bind-Value="_model.Subject"
                              For="@(() => _model.Subject)"
                              Validation="@(_validator.ValidateValue())"
                              Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Start Date</MudText>
                <MudDatePicker @bind-Date="_startDate"
                               Validation="@(async (object value) => await _validator.ValidateValue()(_model, "StartTime"))"
                               Variant="Variant.Outlined" Margin="Margin.Dense" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Start Time</MudText>
                <MudTimePicker @bind-Time="_startTime"
                               Validation="@(async (object value) => await _validator.ValidateValue()(_model, "StartTime"))"
                               Variant="Variant.Outlined" Margin="Margin.Dense" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">End Date</MudText>
                <MudDatePicker @bind-Date="_endDate"
                               Validation="@(async (object value) => await _validator.ValidateValue()(_model, "EndTime"))"
                               Variant="Variant.Outlined" Margin="Margin.Dense" />
            </MudItem>

            <MudItem xs="12" sm="6">
                <MudText Typo="Typo.subtitle2" Class="mb-1">End Time</MudText>
                <MudTimePicker @bind-Time="_endTime"
                               Validation="@(async (object value) => await _validator.ValidateValue()(_model, "EndTime"))"
                               Variant="Variant.Outlined" Margin="Margin.Dense" />
            </MudItem>

            <MudItem xs="12">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Booking Resource</MudText>
                <MudSelect T="string" @bind-Value="_model.BookingResourceId"
                           For="@(() => _model.BookingResourceId)"
                           Validation="@(_validator.ValidateValue())"
                           Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Dense="true">
                    @foreach (var item in _lookupData.Resources)
                    {
                        <MudSelectItem Value="@item.Id">@item.Name</MudSelectItem>
                    }
                </MudSelect>
            </MudItem>

            <MudItem xs="12">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Status</MudText>
                <MudSelect T="Indotalent.Data.Enums.BookingStatus" @bind-Value="_model.Status"
                           Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Dense="true">
                    @foreach (var item in _lookupData.Statuses)
                    {
                        <MudSelectItem Value="@((Indotalent.Data.Enums.BookingStatus)item.Value)">@item.Name</MudSelectItem>
                    }
                </MudSelect>
            </MudItem>

            <MudItem xs="12">
                <MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
                <MudTextField @bind-Value="_model.Description" Variant="Variant.Outlined" Margin="Margin.Dense" Lines="3" FullWidth="true" />
            </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 Booking</MudText>
                }
            </MudButton>
        </div>
    </MudForm>
</MudPaper>

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

    private MudForm _form = default!;
    private CreateBookingValidator _validator = new();
    private CreateBookingRequest _model = new() { Status = Indotalent.Data.Enums.BookingStatus.Draft };
    private LookupBookingDataResponse _lookupData = new();
    private bool _processing = false;

    private DateTime? _startDate = DateTime.Today;
    private TimeSpan? _startTime = DateTime.Now.TimeOfDay;
    private DateTime? _endDate = DateTime.Today;
    private TimeSpan? _endTime = DateTime.Now.TimeOfDay.Add(TimeSpan.FromHours(1));

    protected override async Task OnInitializedAsync()
    {
        var response = await BookingManagerService.GetLookupDataAsync();
        if (response != null && response.IsSuccess)
        {
            _lookupData = response.Value!;
        }
    }

    private async Task Submit()
    {
        if (_startDate.HasValue && _startTime.HasValue)
        {
            _model.StartTime = _startDate.Value.Date.Add(_startTime.Value);
        }
        
        if (_endDate.HasValue && _endTime.HasValue)
        {
            _model.EndTime = _endDate.Value.Date.Add(_endTime.Value);
        }

        await _form.Validate();
        if (!_form.IsValid) return;

        _processing = true;
        try
        {
            var response = await BookingManagerService.CreateBookingAsync(_model);
            await Task.Delay(500);
            if (response != null && response.IsSuccess)
            {
                Snackbar.Add("Booking created successfully", Severity.Success);
                await OnSuccess.InvokeAsync();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Error: {ex.Message}", Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }
}