@page "/user/transfers"
@using AyCode.Models.Messages
@using BlazorAnimation
@using TIAM.Core.Enums
@using TIAM.Entities.ServiceProviders
@using TIAM.Entities.Transfers
@using TIAM.Models.Dtos.Users
@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
@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
@inject ITransferDataService transferDataService
<PageTitle>Transfers</PageTitle>

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

<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="container">
    <div class="row">
        <div class=" col-12">
            <Animation Effect="@Effect.FadeInUp" Class="glass" Speed="@Speed.Fast" Delay="@TimeSpan.FromMilliseconds(250)">
                <div class="card">
                    <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="Grid2"
                                Data="TransferData"
                                AutoCollapseDetailRow="AutoCollapseDetailRow"
                                KeyboardNavigationEnabled="true"
                                CustomizeEditModel="Grid_CustomizeEditModel"
                                EditModelSaving="Grid_EditModelSaving"
                                DataItemDeleting="Grid_DataItemDeleting"
                                EditMode="GridEditMode.EditForm"
                                ColumnResizeMode="GridColumnResizeMode.NextColumn"
                                ShowFilterRow="true"
                                KeyFieldName="Id">

                            <Columns>
                                <DxGridCommandColumn Width="8%" FixedPosition="GridColumnFixedPosition.Left" />
                                <DxGridDataColumn FieldName="Id" SortIndex="0" Visible="false" />
                                <DxGridDataColumn FieldName="OrderId" />
                                <DxGridDataColumn FieldName="FromAddress" />
                                <DxGridDataColumn FieldName="ToAddress" />
                                <DxGridDataColumn FieldName="Appointment" />
                                <DxGridDataColumn FieldName="ContactPhone" />
                                <DxGridDataColumn FieldName="ContactEmail">
                                    <CellDisplayTemplate>
                                        @{
                                            var keyField = context.Value;
                                            var keyItem = (Transfer)context.DataItem;
                                            string buttonText = "Contact";
                                            <DxButton Click="() => SendMail(keyItem)" Text="@buttonText" RenderStyle="ButtonRenderStyle.Primary" />
                                        }
                                    </CellDisplayTemplate>
                                    </DxGridDataColumn>
                                <DxGridDataColumn FieldName="PassengerCount" />
                                <DxGridDataColumn FieldName="TransferStatusType">
                                    <CellDisplayTemplate>
                                        @{
                                            
                                            TransferStatusModel keyField = Statuses.FirstOrDefault(x => x.StatusValue == Convert.ToInt16(context.Value));
                                            string transferStatusText = keyField.StatusName;
                                            <p>@transferStatusText</p>
                                        }
                                    </CellDisplayTemplate>
                                     </DxGridDataColumn>
                            </Columns>
                            <DetailRowTemplate>
                                <Grid_MasterDetail_NestedGrid_DetailContent Customer="(TIAM.Entities.Transfers.Transfer)context.DataItem" KeyboardNavigationEnabled="true" />
                            </DetailRowTemplate>
                            <EditFormTemplate Context="EditFormContext">
                                @{
                                    var transfer2 = (Transfer)EditFormContext.EditModel;
                                }
                                <DxFormLayout CssClass="w-100">
                                    <DxFormLayoutItem Caption=@localizer.GetString(ResourceKeys.DestinationAddress) ColSpanMd="6">
                                        @EditFormContext.GetEditor("ToAddress")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption=@localizer.GetString(ResourceKeys.PickupAddress) ColSpanMd="6">
                                        @EditFormContext.GetEditor("FromAddress")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Trip date:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("Appointment")
                                    </DxFormLayoutItem>
                                    <DxFormLayoutItem Caption="Passengers:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("PassengerCount")
                                    </DxFormLayoutItem>

                                    <DxFormLayoutItem Caption="Status:" ColSpanMd="6">
                                        @EditFormContext.GetEditor("TransferStatusType")
                                    </DxFormLayoutItem>

                                </DxFormLayout>
                            </EditFormTemplate>


                        </DxGrid>

                    </div>

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

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

    </div>
</div>


@code {


    public TransferWizardModel myModel = new TransferWizardModel();

    public List<Transfer> TransferData { get; set; }

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

    public List<TransferStatusModel>? Statuses { get; set; } 

    public MessageWizardModel messageWizardModel = new MessageWizardModel();

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


    void SendMail(Transfer Item)
    {
        logToBrowserConsole.LogToBC($"Sending mail to {Item.ContactEmail}");
        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 transferEditModel = (Transfer)e.EditModel; //TODO not valid cast
            transferEditModel.Id = Guid.NewGuid();
            transferEditModel.ToAddress = "Where to?";
            transferEditModel.FromAddress = "From where?";
            transferEditModel.Appointment = DateTime.UtcNow.AddDays(3);
            transferEditModel.PassengerCount = 1;
            transferEditModel.ContactName = "Full name";
            transferEditModel.ContactPhone = "+00000000000";
            transferEditModel.ContactEmail = "your@email.address";
        }
    }

    async Task Grid_EditModelSaving(GridEditModelSavingEventArgs e)
    {
        if (e.IsNew)
        {
            //add new orderData to orderData array
            logToBrowserConsole.LogToBC("New orderData added");
            //await transferDataService.CreateTransfer((TransferWizardModel)e.EditModel);
        }        
        else
        {
            logToBrowserConsole.LogToBC("orderData updated at id " + ((TransferWizardModel)e.EditModel).Id);
            
            //await transferDataService.UpdateTransferAsync((TransferWizardModel)e.EditModel);
            //modify transferData where transferData.Id == e.EditModel.Id            
        }
        //get transfer from TransferData by Id

        foreach (var transferToModify in (List<Transfer>)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()
    {
        //refresh grid
        //DataSource = await NwindDataService.GetEmployeesEditableAsync();
        logToBrowserConsole.LogToBC("orderData grid refreshed");
    }

    protected override async Task OnInitializedAsync()
    {
        Statuses = new List<TransferStatusModel>
        {
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.OrderSubmitted), "Order submitted"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.OrderConfirmed), "Order confirmed"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.AssignedToDriver), "Assigned to driver"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.DriverConfirmed), "Driver confirmed"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.DriverEnRoute), "Driver enroute"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.PassengerPickup), "Passenger in car"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.Finished), "Finished"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.UserCanceled), "User cancelled"),
            new TransferStatusModel(Convert.ToInt16(TransferStatusType.AdminDenied), "Admin cancelled")
        };
        TransferData = (await transferDataService.GetTransfersAsync()).OrderBy(x => x.TransferStatusType).ThenByDescending(x => x.OrderId).ToList();
        base.OnInitialized();

    }

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

    IGrid Grid2 { get; set; }
    object MasterGridData { get; set; }
    bool AutoCollapseDetailRow { get; set; }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            Grid2.ExpandDetailRow(0);
        }
    }
    void AutoCollapseDetailRow_Changed(bool newValue)
    {
        AutoCollapseDetailRow = newValue;
        if (newValue)
        {
            Grid2.BeginUpdate();
            Grid2.CollapseAllDetailRows();
            Grid2.ExpandDetailRow(0);
            Grid2.EndUpdate();
        }
    }
}



