@page "/user/transfers"
@using AyCode.Models.Messages
@using BlazorAnimation
@using TIAM.Entities.ServiceProviders
@using TIAM.Resources
@using TIAMSharedUI.Pages.Components
@using TIAMSharedUI.Shared
@using TIAMWebApp.Shared.Application.Interfaces
@using TIAMWebApp.Shared.Application.Models
@using TIAMWebApp.Shared.Application.Models.ClientSide.UI.WizardModels
@using TIAMWebApp.Shared.Application.Models.ClientSide.Messages
@using TIAMWebApp.Shared.Application.Utility
@layout AdminLayout
@inject LogToBrowserConsole logToBrowserConsole
@inject IStringLocalizer<TIAMResources> localizer
@inject IWizardProcessor wizardProcessor
<PageTitle>Transfers</PageTitle>

<div class="text-center m-5">
    <h1>Transfer management</h1>
    <h2 style="font-size:small">Manage transfers here!</h2>
</div>

<div class="container">
    <div class="row">
        <div class=" col-12">
            <Animation Effect="@Effect.FadeInUp" Class="glass" Speed="@Speed.Fast" Delay="@TimeSpan.FromMilliseconds(250)">
                <div class="card">

                    <DxPopup CssClass="popup-demo-events"
                             @bind-Visible="@PopupVisible"
                             ShowFooter="true"
                             CloseOnEscape="true"
                             CloseOnOutsideClick="false"
                             ShowCloseButton="false"
                             HeaderText="MessageBox"
                             Closing="EulaPopupClosing"
                             Closed="EulaPopupClosed">
                        <BodyContentTemplate>
                            <InputWizard Data=@messageWizardModel
                                         OnSubmit="SubmitForm"
                                         IgnoreReflection=@ignoreList
                                         TitleResourceString="NewMessage"
                                         SubtitleResourceString="NewMessageSubtitle"
                                         SubmitButtonText="ButtonSend"></InputWizard>
                        </BodyContentTemplate>
                        <FooterContentTemplate Context="Context">
                            <div class="popup-demo-events-footer">
                                <!--DxCheckBox CssClass="popup-demo-events-checkbox" @bind-Checked="@EulaAccepted">I accept the terms of the EULA</!--DxCheckBox-->
                                <!--DxButton CssClass="popup-demo-events-button ms-2" RenderStyle="ButtonRenderStyle.Primary" Text="OK" Click="Context.CloseCallback" /-->
                                <DxButton CssClass="popup-demo-events-button ms-2" RenderStyle="ButtonRenderStyle.Secondary" Text="Cancel" Click="CancelCreateClick" />
                            </div>
                        </FooterContentTemplate>
                    </DxPopup>

                    <div class="d-flex flex-column mb-4 pb-2">
                        <div class="align-self-end pl-2 pb-2">
                            <DxButton Text="Column Chooser"
                                      RenderStyle="ButtonRenderStyle.Secondary"
                                      IconCssClass="btn-column-chooser"
                                      Click="ColumnChooserButton_Click" />
                        </div>
                        <DxGrid @ref="Grid"
                                Data="TransferData"
                                PageSize="8"
                                KeyFieldName="Id"
                                ValidationEnabled="false"
                                CustomizeEditModel="Grid_CustomizeEditModel"
                                EditModelSaving="Grid_EditModelSaving"
                                DataItemDeleting="Grid_DataItemDeleting"
                                EditMode="GridEditMode.EditForm"
                                ColumnResizeMode="GridColumnResizeMode.NextColumn"
                                KeyboardNavigationEnabled="true"
                                ShowFilterRow="true">
                            <Columns>
                                <DxGridCommandColumn Width="8%" FixedPosition="GridColumnFixedPosition.Left" />

                                <DxGridDataColumn FieldName="Id" MinWidth="80" Width="10%" Visible="false" />
                                <DxGridDataColumn FieldName="Destination" FixedPosition="GridColumnFixedPosition.Left" MinWidth="80" Width="10%">
                                    <CellDisplayTemplate>
                                        @{
                                            var keyField = context.Value;
                                            <a class="d-block text-left" href="transferdetails">@context.Value</a>
                                        }
                                    </CellDisplayTemplate>
                                </DxGridDataColumn>
                                <DxGridDataColumn FieldName="PickupAddress" FixedPosition="GridColumnFixedPosition.Left" MinWidth="80" Width="15%" />
                                <DxGridDataColumn FieldName="TripDate" MinWidth="80" Width="10%" />
                                <DxGridDataColumn FieldName="NumberOfPassengers" MinWidth="40" Width="3%" />
                                <DxGridDataColumn FieldName="FullName" MinWidth="80" />
                                <DxGridDataColumn FieldName="PhoneNumber" MinWidth="80" Width="10%" />
                                <DxGridDataColumn FieldName="EmailAddress" MinWidth="80" Width="10%">
                                    <CellDisplayTemplate>
                                        @{
                                            var keyField = context.Value;
                                            var keyItem = (TransferWizardModel)context.DataItem;
                                            string buttonText = "Contact";
                                            <DxButton Click="() => SendMail(keyItem)" Text="@buttonText" RenderStyle="ButtonRenderStyle.Primary" />
                                        }
                                    </CellDisplayTemplate>
                                </DxGridDataColumn>
                                <DxGridDataColumn FieldName="Driver" FixedPosition="GridColumnFixedPosition.Right" MinWidth="80" Width="15%">
                                    <CellDisplayTemplate>
                                        @{
                                            DriverModel keyField = (DriverModel)context.Value;
                                            string driverText = keyField.Name;
                                            <p>@driverText</p>
                                        }
                                    </CellDisplayTemplate>
                                </DxGridDataColumn>

                            </Columns>

                            <EditFormTemplate Context="EditFormContext">
                                @{
                                    var transfer = (TransferWizardModel)EditFormContext.EditModel;
                                }
                                <DxFormLayout CssClass="w-100">
                                    <DxFormLayoutItem Caption=@localizer.GetString(ResourceKeys.DestinationAddress) ColSpanMd="6">
                                        @EditFormContext.GetEditor("Destination")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption=@localizer.GetString(ResourceKeys.PickupAddress) ColSpanMd="6">
                                        @EditFormContext.GetEditor("PickupAddress")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Trip date:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("TripDate")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Passengers:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("NumberOfPassengers")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Full name:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("FullName")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Phone number:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("PhoneNumber")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Email:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("EmailAddress")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Driver:" ColSpanMd="6">
                                        <DxComboBox Data="@drivers"
                                                    NullText="Select driver..."
                                                    FilteringMode="DataGridFilteringMode.Contains"
                                                    TextFieldName="Name"
                                                    ValueFieldName="Name"
                                                    Value="@transfer.Driver.Name"
                                                    ValueChanged="(string newCellValue) => {
                                                transfer.Driver = drivers.FirstOrDefault(x => x.Name == newCellValue);
                                                logToBrowserConsole.LogToBC(newCellValue);
                                          }">
                                        </DxComboBox>
                                    </DxFormLayoutItem>

                                </DxFormLayout>
                            </EditFormTemplate>

                        </DxGrid>


                    </div>




                </div>
            </Animation>
        </div>

        <div class=" col-12 col-xl-6">
        </div>

    </div>
</div>


@code {

    IGrid Grid { get; set; }
    //object? TransferData { get; set; }

    public TransferWizardModel myModel = new TransferWizardModel();

    bool PopupVisible { get; set; }
    public List<string> ignoreList = new List<string>
    {
        "ReceiverEmailAddress",
         "ReceiverId",
         "SenderEmailAddress",
         "SenderId",
         "ContextId"
    };

    public MessageWizardModel messageWizardModel = new MessageWizardModel();


    //IEnumerable<DriverModel> drivers { get; set; }

    IEnumerable<DriverModel> drivers { get; set; } = new DriverModel[] {
                                        new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "John Doe"),
                                        new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "Jane Doe"),
                                        new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "James Doe")
                        };

    object? TransferData = new TransferWizardModel[]
    {
    new TransferWizardModel(Guid.NewGuid(), "1087, Budapest, Százados út 30/a", "Nyugati Pályaudvar", DateTime.UtcNow.AddDays(3), 3, "John Malkovich", "+13021234567", "john.malkovich@stars.com", new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "John Doe")),
    new TransferWizardModel(Guid.NewGuid(), "1027, Budapest, Batthyányi tér 3", "Budapest, Koós Károly sétány 21", DateTime.UtcNow.AddDays(6), 3, "John Malkovich", "+13021234567", "john.malkovich@stars.com", new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "Jane Doe")),
    new TransferWizardModel(Guid.NewGuid(), "1087, Budapest, Százados út 30/a", "Nyugati Pályaudvar", DateTime.UtcNow.AddDays(2), 3, "John Malkovich", "+13021234567", "john.malkovich@stars.com", new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "James Doe")),
    new TransferWizardModel(Guid.NewGuid(), "1087, Budapest, Százados út 30/a", "Nyugati Pályaudvar", DateTime.UtcNow.AddDays(4).AddHours(-6), 3, "John Malkovich", "+13021234567", "john.malkovich@stars.com", new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "James Doe")),
    new TransferWizardModel(Guid.NewGuid(), "1087, Budapest, Százados út 30/a", "Nyugati Pályaudvar", DateTime.UtcNow.AddDays(7), 3, "John Malkovich", "+13021234567", "john.malkovich@stars.com", new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "Joan Doe")),
    new TransferWizardModel(Guid.NewGuid(), "1087, Budapest, Százados út 30/a", "Nyugati Pályaudvar", DateTime.UtcNow.AddDays(1), 3, "John Malkovich", "+13021234567", "john.malkovich@stars.com", new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "James Doe")),
    new TransferWizardModel(Guid.NewGuid(), "1087, Budapest, Százados út 30/a", "Nyugati Pályaudvar", DateTime.UtcNow.AddDays(6).AddHours(3), 3, "John Malkovich", "+13021234567", "john.malkovich@stars.com", new DriverModel(Guid.NewGuid(), Guid.NewGuid(), "John Doe"))

    };

    void SendMail(TransferWizardModel Item)
    {
        logToBrowserConsole.LogToBC($"Sending mail to {Item.EmailAddress}");
        PopupVisible = true;
    }

    void CancelCreateClick()
    {


        PopupVisible = false;
    }
    void EulaPopupClosed()
    {
        //cancel clicked

    }
    void EulaPopupClosing(PopupClosingEventArgs args)
    {
        //myModel = new TransferWizardModel();
        messageWizardModel = new MessageWizardModel();
    }

    //-----------------------------------------------------------------------------------


    public async Task SubmitForm(object Result)
    {
        var email = await wizardProcessor.ProcessWizardAsync<MessageWizardModel>(Result.GetType(), Result);

        logToBrowserConsole.LogToBC($"Submitted nested form: {Result.GetType().FullName}");
    }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        //if (firstRender)
        //    await Grid.StartEditRowAsync(0);
    }

    void Grid_CustomizeEditModel(GridCustomizeEditModelEventArgs e)
    {
        if (e.IsNew)
        {
            var newEmployee = (TransferWizardModel)e.EditModel;
            newEmployee.Id = Guid.NewGuid();
            newEmployee.Destination = "ghjgkg hkgh ghjkghgkjgh";
            newEmployee.PickupAddress = "ghjgkg hkgh ghjkghgkjgh";
            newEmployee.TripDate = DateTime.UtcNow.AddDays(3);
            newEmployee.NumberOfPassengers = 1;
            newEmployee.FullName = "ghjgkg hkgh ghjkghgkjgh";
            newEmployee.PhoneNumber = "+13021234567";
            newEmployee.EmailAddress = "ghjgkg hkgh ghjkghgkjgh";
            newEmployee.Driver = drivers.FirstOrDefault();
        }
    }

    async Task Grid_EditModelSaving(GridEditModelSavingEventArgs e)
    {
        if (e.IsNew)
            //add new orderData to orderData array
            logToBrowserConsole.LogToBC("New orderData added");
        //await NwindDataService.InsertEmployeeAsync((EditableEmployee)e.EditModel);
        else
            logToBrowserConsole.LogToBC("orderData updated");
        //modify transferData where transferData.Id == e.EditModel.Id
        //get transfer from TransferData by Id

        foreach (var transferToModify in (TransferWizardModel[])TransferData)
        {
            myModel = (TransferWizardModel)e.EditModel;

            if (transferToModify.Id == myModel.Id)
            {
                transferToModify.Driver = myModel.Driver;
            }
        }



        //await NwindDataService.UpdateEmployeeAsync((EditableEmployee)e.DataItem, (EditableEmployee)e.EditModel);

        await UpdateDataAsync();
    }
    async Task Grid_DataItemDeleting(GridDataItemDeletingEventArgs e)
    {
        //await NwindDataService.RemoveEmployeeAsync((EditableEmployee)e.DataItem);
        //remove orderData from orderData array
        logToBrowserConsole.LogToBC("orderData deleted");
        //await UpdateDataAsync();
    }
    async Task UpdateDataAsync()
    {
        //DataSource = await NwindDataService.GetEmployeesEditableAsync();
        //refresh grid
        logToBrowserConsole.LogToBC("orderData grid refreshed");
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();




    }

    void ColumnChooserButton_Click()
    {
        Grid.ShowColumnChooser();
    }

}
